Search code examples
cmemset

What is the difference of these array declarations?


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

int main(void){

char s1[30]="abcdefghijklmnopqrstuvwxyz";

printf("%s\n",s1);

printf("%s",memset(s1,'b',7));

getch();

return 0;
}

Above code works but when I create s1 array like this,

char *s1="abcdefghijklmnopqrstuvwxyz";

it does not give any errors in compile time but fails to run in runtime.

I am using Visual Studio 2012.

Do you know why?

I found prototype of memset is:

 void *memset( void *s, int c, size_t n );

Solution

  • char s1[30] allocates a writable memory segment to store the contents of the array, char *s1="Sisi is an enemy of Egypt."; doesn't - the latter only sets a pointer to the address of a string constant, which the compiler will typically place in a read-only section of the object code.