Difference between char * and char [] with strcpy ()

I had problems with the last couple of hours for the problem, although I understood. Here is my problem:

void cut_str(char* entry, int offset) {
    strcpy(entry, entry + offset);
}

char  works[128] = "example1\0";
char* doesnt = "example2\0";

printf("output:\n");

cut_str(works, 2);
printf("%s\n", works);

cut_str(doesnt, 2);
printf("%s\n", doesnt);

// output:
// ample1
// Segmentation: fault

It seems to me that there is something important in char * / char [] that I am not getting here.

+5
source share
3 answers

The difference is that it doesntpoints to memory that belongs to a string constant and therefore is not writable.

When you do it

char  works[128] = "example1\0";

the compiler copies the contents of the string without writing to the writable array. \0not required, by the way.

If you do this,

char* doesnt = "example2\0";

the compiler leaves a pointer pointing to an area of ​​non-writable memory. Again, it \0will be inserted by the compiler.

gcc, char * . -Wwrite-strings. , :

 warning: initialization discards qualifiers from pointer target type

doesnt :

const char* doesnt = "example2\0";
+11

char[] char * , . , , . works, char[], 128 , . doesnt, char *, .

doesnt C, , , , , . . , segfault, .

+4

128 works :

char works[128];

So works - .

, , doesnt :

char * doesnt = "example2\0";

works, . doesnt, .

Also note that you do not need to end string literals with "\0", since all string literals implicitly add a null byte to the end of the string.

+3
source

All Articles