Reputation:
Why is the following code invalid?
void foo()
{
char hello[6];
char *foo = "hello";
hello = foo;
}
But how the following code is valid?
void foo()
{
char hello[] = "hello";
char *foo = hello;
}
Upvotes: 1
Views: 154
Reputation: 56479
I think you supposed string "hello"
will be copied to hello
. It's wrong. You're trying to assign a pointer to another. And, you can not assign to hello
.
The right way is:
strcpy(hello, foo);
Upvotes: 3
Reputation: 43
In first case you are assigning string to a foo pointer that is wrong. where as in 2nd case you have an array of char and you are passing it into foo pointer
Upvotes: 0
Reputation: 15553
You are are trying to assign the array as a pointer. This is invalid. Arrays are like pointer constants in that they can’t be used as lvalues – they can’t be reassigned to point to somewhere else. The closest you can get is to copy the contents of foo into hello.
In second case, hello is an array of chars and foo is a pointer to a char. In general, arrays are interchangeable with pointers of the same type so this is valid.
Upvotes: 3