0

I don't understand this thing. about memset in C

  1. I stored john in array[].
  2. Then I created char* megaArray[10] which can store 10 strings.
  3. I assigned megaArray[0] = array. So john gets stored in 0 position of megaArray[].
  4. I called memset() to reset array[]. array gets emptied.
  5. Why does tokens[0] gets emptied if I called memset() for array[] ?

Please Help,

Here is the code

#include <stdio.h>

int main() {
    char array[] = "john";
    printf("%s is the name\n",array);
    
    char* megaArray[10];
    megaArray[0] = array;
    
    printf("%s is the name in mega Array\n",megaArray[0]);
    
    memset(array, '\0', sizeof(array));
    
    printf("%s is the name after memset\n",array);
    
    printf("'%s' is the name in mega Array after memset\n",megaArray[0]);
    
    
    return 0;
}

3 Answers3

2

The assignment

megaArray[0] = array;

doesn't create a copy of array.

Instead it makes megaArray[0] point to (the first element of) array. It's equivalent to:

megaArray[0] = &array[0];

Somewhat graphically it looks like this (after the assignment):


+--------------+     +----------+----------+-----+----------+
| megaArray[0] | --> | array[0] | array[1] | ... | array[4] |
+--------------+     +----------+----------+-----+----------+
| megaArray[1] | --> ?
+--------------+
| ...          |
+--------------+
| megaArray[9] | --> ?
+--------------+
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1
char* megaArray[10];

is an array of char-pointers. So when you assign

megaArray[0] = array;

You let the first array element "point" to the string stored in the variable array. It does not copy the string. megaArray[0] now contains an address to array and its literaly the same string at the same memory location. So memsetting array changes one and the same string.

Danny Raufeisen
  • 953
  • 8
  • 21
0

char* megaArray[10]; is simple array of pointers.

megaArray[0] = array; it assigns the pointer megaArray[0] with reference (address) of array. It does not allocate new memory or copy the data.

printf("'%s' is the name in mega Array after memset\n",megaArray[0]);

prints the array which was zeroed by memset as megaArray[0] contains a pointer to array

If you want to make the copy of the string held in array

megaArray[0] = strdup(array);

or

megaArray[0] = malloc(sizeof(array));
memcpy(megaArray[0], array, sizeof(array));
0___________
  • 60,014
  • 4
  • 34
  • 74