0

For some reason, I get a compiler error whenever I try to set the value of a C string to a string literal:

#include <stdio.h>

int main(void) {
    char hi[] = "Now I'm initializing a string.";
    hi = "This line doesn't work!"; //this is the line that produced the compiler error
    return 0;
}

Also, these are the compiler errors:

prog.c: In function ‘main’:
prog.c:5:8: error: incompatible types when assigning to type ‘char[31]’ from type ‘char *’
prog.c:4:10: warning: variable ‘hi’ set but not used [-Wunused-but-set-variable]

What can I do to fix this problem?

Anderson Green
  • 30,230
  • 67
  • 195
  • 328
  • @OliCharlesworth It appears that the other question is less straightforward than this one (and not as easy to read), so I'm not sure if these questions should be merged. – Anderson Green Apr 09 '13 at 19:59

3 Answers3

3

The way to copy a string is the strcpy() function:

strcpy(hi, "This line should work");

Beware: This doesn't check that there's enough room in the target to hold the string. (And no, strncpy() is probably not the solution.

C does not permit assignment of arrays.

Recommended reading: Section 6 of the comp.lang.c FAQ.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
0

Ok, what's happening here is this,

when you write

hi = "something here";

what happens is, in the memory, the string "something here" is stored, and it returns the pointer to the first element in the memory where the string is stored.

So, it expects the lvalue to be a pointer to char , and not a array of char itself.

So, hi must be declared as char* hi

cipher
  • 2,414
  • 4
  • 30
  • 54
0

Try this:

char hi[100];
strlcpy(hi, "something here", sizeof(hi));

you should use strlcpy() because strcpy() and strncpy() are not safe.

See : strncpy or strlcpy in my case

Community
  • 1
  • 1
  • Use `sizeof hi`, not `100`. Note that `strlcpy()` is not part of the C standard (nor is it POSIX), so it may or may not be available. – Keith Thompson Apr 09 '13 at 19:59
  • Thank you for the feedback. I replaced 100 by sizeof(hi). If `strlcpy` is not available, maybe the OP can use `strcpy`. Both can be an answer to the question. If `strlcpy` is available, best is to use it. –  Apr 09 '13 at 20:03