2

I'm currently playing a bit with C and trying to understand strings. Can somebody please explain why this is working:

char test[] = "test";

And why the following does not?

char test[255];
test = "test";

6 Answers 6

8

Because this is an initialization:

char test[] = "test";

and this is an assignment:

test = "test";

and you cannot assign arrays in C (and strings in C are just arrays).

Your best bet is to copy the string using strcpy() (or to be safe, strncpy()).

Sign up to request clarification or add additional context in comments.

Comments

5

C doesn't allow you to assign values to an entire array except when it's initialized.

The correct way to copy a string into an existing array is with strcpy:

char test[255];
strcpy(test,"test");

Comments

0

even though what you say looks obvious,it is incorrect.you can't directly assign a string to a character array.you could try and use strcpy() function.

Comments

0

Because "test" is a pointer and test is an array. You can always use strcpy() though.

Comments

0

Unfortunately C doesnot support direct assigment of string(As it invloves more than 1 memory address). You must rather use strcpy or memcpy functions.

well yeah

 test[0]='t' works (since your accessing one memory location at the time)

Comments

0

You can't assign an array directly because it is an unmodifiable lvalue. But you can use an indirectly assignment like:

typedef struct { char s[100]; } String;

int main()
{
  char a[100] = "before";
  assert( sizeof a >= sizeof(String) );
  puts( a );
  *(String*)a = *(String*) "after";
  puts( a );
  return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.