2

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;

1
  • Would that huge value be 16843009? (Telling us that would have been helpful.) Commented May 3, 2012 at 22:44

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

So if the int array was not inside the struct I could use memset, but not otherwise? Could I use a pointer to the array and then use memset (not stuck on using memset, just trying to figure out why).
You can never use memset. It assigns the same value to every byte in the array. But you want to assign 0x00000001.
Now I get it. So memset is only really useful for initializing a block of memory to a single char. Presumably the code would work if all I wanted to do was set all the values to 0.
No. You would have to use: sizeof(int)*9000 instead of 9000, otherwise not every byte would be set to zero, only the first 9000/sizeof(int) int's would be set to zero.
1

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.

1 Comment

I understand what you are saying about wmemset. But I am not a nasty boy, and will refrain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.