Search code examples
ccstringstrcpy

Need explanation of Word2 variable


I DO UNDERSTAND THAT THIS PROGRAM IS NOT ALLOCATING ENOUGH MEMORY.

What I need help with is describing an explanation of what happens when this code is executed.

I put "Since only 4 spaces are allocated it is not given enough space so it causes an error." Which doesn't sound right to me. Thanks.

#include <stdio.h> 
#include <string.h>

int main()
{ 
    char word1[20];
    char *word2;

    word2 = (char*)malloc(sizeof(char)*20);

    printf("Sizeof word 1: %d\n", sizeof (word1));  //This line outputs 20
    printf("Sizeof word 2: %d\n", sizeof (word2));  //This line outputs 4
                                                    //before & after I used malloc
    strcpy(word1, "string number 1");
    strcpy(word2, "string number 2"); <---- What is this doing

    printf("%s\n", word1);
    printf("%s\n", word2);
}

Solution

  • sizeof( word2 ) returns 4 because that is the size of the pointer

    char *word2;
    

    is a pointer and there is 0 Bytes allocated for it ( not 4 as you mentioned)

    sizeof( word1 ) returns 20 becuase that is the size of array

    char word1[20]
    

    is an array and there is 20 Bytes reserved for it