memset 的替代方案
我想初始化一个结构体数组,但是 memset() 的第二个参数采用 int 。是否还有另一个函数具有相同的功能,但 (void *) 有第二个参数? 我想到了 memcpy() 但它没有设置整个数组中的值。有什么想法吗?
结构:
typedef struct {
int x;
int y;
char *data;
} my_stuff;
代码:
my_stuff my_array[];
my_array = malloc(MAX * sizeof(my_stuff));
my_stuff *tmp;
tmp->x = -1;
tmp->y = 1;
strcpy(tmp->data = "Initial state");
memset(my_array, tmp, sizeof(my_array));
I want to initialize an array of struct, however the second parameter of memset() takes an int. Is there another the function that does the same but with a (void *) has 2nd parameter?
I thought of memcpy() but it doesn't set the value in the entire array. Any idea?
the struct:
typedef struct {
int x;
int y;
char *data;
} my_stuff;
The code:
my_stuff my_array[];
my_array = malloc(MAX * sizeof(my_stuff));
my_stuff *tmp;
tmp->x = -1;
tmp->y = 1;
strcpy(tmp->data = "Initial state");
memset(my_array, tmp, sizeof(my_array));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
memset()
设置每个字节的值。将指针类型转换为整数(第二个参数)是没有问题的。主要问题是它会大于一个字节。我不知道有任何版本的
memset()
复制的内容多于字节值。我会为此创建一个简单的循环。另请注意,如果您的代码有效,还会出现一些其他问题。一方面,
sizeof(my_array)
返回数据结构中的字节总数,而不是元素数量。另外,您的代码只是复制了指针。您需要实际复制它指向的数据,因为目标不是指针,而是实际的结构。memset()
sets the value of each byte. There's no problem typecasting a pointer to an integer (the second parameter). The main problem is that it will be bigger than a byte.I'm not aware of any version of
memset()
that copies more than byte values. I would create a simple loop for this.Also note that there would be some additional problems with your code, had it worked. For one thing,
sizeof(my_array)
returns the total number of bytes in the data structure and not the number of elements. Also, your code would've just copied the pointer. You need to actually copy the data it points to since the target is not pointers--it's actual structures.没有为此的标准函数 - 您只需要在循环中调用
memcpy()
即可:请注意,您不能将
strcpy()
调用到tmp.data
,因为这只是一个没有分配内存的悬空指针。There isn't a standard function for this - you will just need to call
memcpy()
in a loop:Note that you can't
strcpy()
intotmp.data
, because that's just a dangling pointer with no memory allocated.在这种情况下不能使用 memset()。您应该使用 memcpy()。试试这个:
1. malloc你的数组
2.初始化数组的第一个元素
3.将第一个元素复制到所有元素
You cannot use memset() in this case. You should use memcpy(). Just try this out:
1. malloc your array
2. initialize the first element of the array
3. copy the first element to all the elements