c++ - What is the difference between these two strings? -


this question has answer here:

part 1

i have 2 strings , defined in following ways-

char s1[] = "foo"; char *s2 = "foo"; 

when try change character of these strings, say, 2nd character -

char s1[1] = 'x'; char s2[1] = 'x'; 

the character in string s1 changes, changing character in string s2 gives me error - segmentation fault (core dumped).

why so?

why unable change character of string defined in other way?


part 2

strings (they array of characters, right?) can initialized using - char *s = "foo" why compiler gives warnings when try initialize arrays of different type using same thing int *arr = {1, 2, 3}?

foo.c: in function ‘main’: foo.c:5:5: warning: initialization makes pointer integer without cast [enabled default] foo.c:5:5: warning: (near initialization ‘foo’) [enabled default] foo.c:5:5: warning: excess elements in scalar initializer [enabled default] foo.c:5:5: warning: (near initialization ‘foo’) [enabled default] foo.c:5:5: warning: excess elements in scalar initializer [enabled default] foo.c:5:5: warning: (near initialization ‘foo’) [enabled default] 

note: compiler gcc.

the first 1 string array of characters, filled characters in string "foo", second 1 pointer constant value "foo". since second 1 constant, isn't allowed modify it.

and no, can't initialize pointer set of values - because pointer has no actual memory store values assigned it. need either make point array:

int foox[3] = { 1, 2, 3 }; int *foo = foox; 

or need allocate memory, , store values:

int *foo = malloc(sizeof(int) * 3);  foo[0] = 1;  foo[1] = 2;  foo[2] = 3;  

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -