Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

Using memset for integer array in C

char str[] = "beautiful earth";
memset(str, '*', 6);
printf("%s", str);

Output:
******ful earth

Like the above use of memset, can we initialize only a few integer array index values to 1 as given below?

int arr[15];
memset(arr, 1, 6);
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, you cannot use memset() like this. The manpage says (emphasis mine):

The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c.

Since an int is usually 4 bytes, this won't cut it.


If you (incorrectly!!) try to do this:

int arr[15];
memset(arr, 1, 6*sizeof(int));    //wrong!

then the first 6 ints in the array will actually be set to 0x01010101 = 16843009.

The only time it's ever really acceptable to write over a "blob" of data with non-byte datatype(s), is memset(thing, 0, sizeof(thing)); to "zero-out" the whole struture/array. This works because NULL, 0x00000000, 0.0, are all completely zeros.


The solution is to use a for loop and set it yourself:

int arr[15];
int i;

for (i=0; i<6; ++i)    // Set the first 6 elements in the array
    arr[i] = 1;        // to the value 1.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...