سؤال

This should copy a string but prints garbled results. Can anyone help me out?

int main () {       

    const char *a = "Hello\n";
    const char *b = "World\n";

    strncpy(&b, &a, strlen(a)); 
    printf("%s %s", a, b);  
    return 0;

}

I expect "Hello Hello" but the terminal prints:

\
    Hello

GCC prints an warning about a and b having incompatible pointer types even though strncpy's signature:

char * strncpy(char *s1, const char *s2, size_t n)

asks for 2 char pointers. Is that because arrays are always char** as mentioned in https://stackoverflow.com/a/20213168 ?

هل كانت مفيدة؟

المحلول

You are passing char ** twice where char* is expected.

&b takes the address of b, with b being a char*, the address of a char. So &b is char **. The same issue appears for a.


Update:

Just saw b isn't an array but a pointer which points to a "string"-literal. The latter are constant, you cannot change them, so copying to a literal's address (what the code actually does not, because of the misplaced &-operator in frot of the b) has to fail.

To get around this define b like this

char b [] = "World\n";

Is that because arrays are always char** [...]

Arrays aren't "always char **".

If an array is passed as argument to a function it decays to a pointer to it's first element. So

char b[] = "test";

would decay to a

char * pb

with pb pointing to the char 't', the first characters of `"test".

نصائح أخرى

Two problems:

  1. You should not copy into a buffer pointed by const char *, as it is a constant buffer.
  2. The arguments for strncpy are char *s, but you passed char **, thus overwriting the pointers themselves, not the content they point to.

Compile your code with -Wall to see warnings that will tell you how to fix this.

Two issues:

1) You should use strncpy(a, b, strlen(a)), if a is a char* and b a const char*. The compiler error you're getting alludes to this.

2) You have undefined behaviour. You've allocated const char* string literals. A compiler may put them in read-only memory. And an attempt to modify either of them is not allowed: even a single element change could cause a program crash.

One remedy would be to use char* b = malloc(/*ToDo - your size here*/);. Remember to free the memory once you're done with it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top