Reputation: 2106
Let's say I have a char pointer called string1 that points to the first character in the word "hahahaha". I want to create a char[] that contains the same string that string1 points to.
How come this does not work?
char string2[] = string1;
Upvotes: 1
Views: 28954
Reputation: 300489
"How come this does not work?"
Because that's not how the C language was defined.
You can create a copy using strdup()
[Note that strdup()
is not ANSI C]
Refs:
Upvotes: 3
Reputation: 683
What you write like this:
char str[] = "hello";
... actually becomes this:
char str[] = {'h', 'e', 'l', 'l', 'o'};
Here we are implicitly invoking something called the initializer.
Initializer is responsible for making the character array, in the above scenario.
Initializer does this, behind the scene:
char str[5];
str[0] = 'h';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
C is a very low level language. Your statement:
char str[] = another_str;
doesn't make sense to C.
It is not possible to assign an entire array, to another in C. You have to copy letter by letter, either manually or using the strcpy() function.
In the above statement, the initializer does not know the length of the another_str
array variable. If you hard code the string instead of putting another_str
, then it will work.
Some other languages might allow to do such things... but you can't expect a manual car to switch gears automatically. You are in charge of it.
Upvotes: 0
Reputation: 4433
In C you have to reserve memory to hold a string.
This is done automatically when you define a constant string, and then assign to a char[].
On the other hand, when you write string2 = string1
,
what you are actually doing is assigning the memory addresses of pointer-to-char objects. If string2
is declares as char*
(pointer-to-char), then it is valid the assignment:
char* string2 = "Hello.";
The variable string2
now holds the address of the first character of the constanta array of char "Hello.".
It is fine, also, to write string2 = string1 when string2
is a char*
and string1
is a char[]
.
However, it is supposed that a char[]
has constant address in memory. Is not modifiable.
So, it is not allowed to write sentences like that:
char string2[];
string2 = (something...);
However, you are able to modify the individual characters of string2, because is an array of characters:
string2[0] = 'x'; /* That's ok! */
Upvotes: -1
Reputation: 1005
1) pointer string2 == pointer string1
change in value of either will change the other
From poster poida
char string1[] = "hahahahaha";
char* string2 = string1;
2) Make a Copy
char string1[] = "hahahahaha";
char string2[11]; /* allocate sufficient memory plus null character */
strcpy(string2, string1);
change in value of one of them will not change the other
Upvotes: 0