简体   繁体   中英

memset array inside structure c

I'm trying to memset an array of ints that exist inside a structure:

typedef struct _xyz {
    int zList[9000];
} xyz;

int dll_tmain(void)
{
    xyz *Xyz       =  (xyz *) calloc(10, sizeof(xyz));
    memset((&Xyz[0])->zList, 1, 9000);
}

I've tried a lot of variations in the memset(), to no avail. Instead of being initialized to 1, the number is some huge value;

Remember that memset sets each byte of an array to the same value. So you are copying, to the first 9000 bytes of the array, the byte with value 1. Assuming 4 byte integers, that means you are assigning an int with value 0x01010101 . But, what's more, you are not assigning to the entire array, only the first 1/4 of it, again assuming 4 byte integers.

You can't do what you want with memset . Use a for loop instead.

The 'value' you want to set is passed to memset as an int, but memset 'fills the block of memory using the unsigned char conversion of this value' one byte at a time.

So you are filling the first 9000 bytes to the value 0x01. int's will generally be 2, 4 or 8 bytes, not 1 byte.

Just write your own loop to do it. If you don't want to write your own for some reason, check if your system has wmemset, then check if your wchar_t is the same size as int, then you can be nasty and use wmemset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM