Assigning strings to arrays of characters
I am a little surprised by the following.
Example 1:
char s[100] = "abcd"; // declare and initialize - WORKS
Example 2:
char s[100]; // declare
s = "hello"; // initalize - DOESN'T WORK ('lvalue required' error)
I'm wondering why the second approach doesn't work. It seems natural that it should (it works with other data types)? Could someone explain me the logic behind this?
c
add a comment |
I am a little surprised by the following.
Example 1:
char s[100] = "abcd"; // declare and initialize - WORKS
Example 2:
char s[100]; // declare
s = "hello"; // initalize - DOESN'T WORK ('lvalue required' error)
I'm wondering why the second approach doesn't work. It seems natural that it should (it works with other data types)? Could someone explain me the logic behind this?
c
add a comment |
I am a little surprised by the following.
Example 1:
char s[100] = "abcd"; // declare and initialize - WORKS
Example 2:
char s[100]; // declare
s = "hello"; // initalize - DOESN'T WORK ('lvalue required' error)
I'm wondering why the second approach doesn't work. It seems natural that it should (it works with other data types)? Could someone explain me the logic behind this?
c
I am a little surprised by the following.
Example 1:
char s[100] = "abcd"; // declare and initialize - WORKS
Example 2:
char s[100]; // declare
s = "hello"; // initalize - DOESN'T WORK ('lvalue required' error)
I'm wondering why the second approach doesn't work. It seems natural that it should (it works with other data types)? Could someone explain me the logic behind this?
c
c
edited Feb 23 '09 at 22:54
Ree
asked Feb 23 '09 at 22:47
ReeRee
3,288104150
3,288104150
add a comment |
add a comment |
9 Answers
9
active
oldest
votes
When initializing an array, C allows you to fill it with values. So
char s[100] = "abcd";
is basically the same as
int s[3] = { 1, 2, 3 };
but it doesn't allow you to do the assignment since s is an array and not a free pointer. The meaning of
s = "abcd"
is to assign the pointer value of abcd to s but you can't change s since then nothing will be pointing to the array.
This can and does work if s is a char* - a pointer that can point to anything.
If you want to copy the string simple use strcpy.
4
Good answer, except you should never use plain strcpy any longer. Use strncpy or strlcpy.
– dwc
Feb 23 '09 at 23:01
3
Also, s should be const char*, not char*.
– aib
Feb 24 '09 at 14:17
1
s[0] = 'x'; s[1] = 'y'; s[2] = 'z'; s[3] = 'm';works if one wants to replace the string characters one by one even after initialization.
– RBT
Oct 28 '16 at 2:44
@RBT, maybe it does in your platform with your compilation flags but often times these strings are defined in read-only memory. writing to it would cause a segfault or an Access-Violation error
– shoosh
Dec 4 '16 at 7:52
Why? Doingchar s[100]; s = "abcd";gives error makes perfect sense because s is effectively treated as a const pointer. So if we try assigning "abcd" in second line we are trying to change the value of the pointer which is not allowed. But if a const pointer is pointing to a memory location then the contents of the memory location should of course be modifiable. Let's sayspoints to memory location 1000 then s contains 1000 and memory location # 1000 contains a. I can't change s to store new memory location e.g. 2000 but I can store a new character e.g. z at memory location 1000.
– RBT
Dec 5 '16 at 3:46
|
show 2 more comments
There is no such thing as a "string" in C. In C, strings are one-dimensional array of char, terminated by a null character . Since you can't assign arrays in C, you can't assign strings either. The literal "hello" is syntactic sugar for const char x = {'h','e','l','l','o',''};
The correct way would be:
char s[100];
strncpy(s, "hello", 100);
or better yet:
#define STRMAX 100
char s[STRMAX];
size_t len;
len = strncpy(s, "hello", STRMAX);
2
Not the recommended approach. Beware of the oddities of strncpy: stackoverflow.com/a/1258577/2974922
– nucleon
Feb 23 '17 at 10:40
I think this approach could easily be recommended
– Volt
Oct 12 '18 at 8:00
add a comment |
Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.
add a comment |
1 char s[100];
2 s = "hello";
In the example you provided, s is actually initialized at line 1, not line 2. Even though you didn't assign it a value explicitly at this point, the compiler did. At line 2, you're performing an assignment operation, and you cannot assign one array of characters to another array of characters like this. You'll have to use strcpy() or some kind of loop to assign each element of the array.
add a comment |
To expand on Sparr's answer
Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.
Think of it like this:
Imagine that there are 2 functions, called InitializeObject, and AssignObject. When the compiler sees thing = value, it looks at the context and calls one InitializeObject if you're making a new thing. If you're not, it instead calls AssignObject.
Normally this is fine as InitializeObject and AssignObject usually behave the same way. Except when dealing with char arrays (and a few other edge cases) in which case they behave differently. Why do this? Well that's a whole other post involving the stack vs the heap and so on and so forth.
PS: As an aside, thinking of it in this way will also help you understand copy constructors and other such things if you ever venture into C++
add a comment |
Note that you can still do:
s[0] = 'h';
s[1] = 'e';
s[2] = 'l';
s[3] = 'l';
s[4] = 'o';
s[5] = '';
It's much nicer and easier to use strncpy(), even though I'm pretty sure strncpy() does exactly this internally.
– Chris Lutz
Feb 24 '09 at 14:33
Of course. But this is as close as it gets to 's = "hello";' In fact, this should have been implemented in C, seeing as how you can assign structs.
– aib
Feb 24 '09 at 14:47
I mean, memberwise copy by assignment in structs but not in arrays doesn't make sense.
– aib
Feb 24 '09 at 14:49
add a comment |
I know that this has already been answered, but I wanted to share an answer that I gave to someone who asked a very similar question on a C/C++ Facebook group.
Arrays don't have assignment operator functions*. This means that you cannot simply assign a char array to a string literal. Why? Because the array itself doesn't have any assignment operator. (*It's a const pointer which can't be changed.)
arrays are simply an area of contiguous allocated memory and the name
of the array is actually a pointer to the first element of the array.
(Quote from https://www.quora.com/Can-we-copy-an-array-using-an-assignment-operator)
To copy a string literal (such as "Hello world" or "abcd") to your char array, you must manually copy all char elements of the string literal onto the array.
char s[100]; This will initialize an empty array of length 100.
Now to copy your string literal onto this array, use strcpy
strcpy(s, "abcd"); This will copy the contents from the string literal "abcd" and copy it to the s[100] array.
Here's a great example of what it's doing:
int i = 0; //start at 0
do {
s[i] = ("Hello World")[i]; //assign s[i] to the string literal index i
} while(s[i++]); //continue the loop until the last char is null
You should obviously use strcpy instead of this custom string literal copier, but it's a good example that explains how strcpy fundamentally works.
Hope this helps!
add a comment |
You can use this:
yylval.sval=strdup("VHDL + Volcal trance...");
Where
yylval is char*. strdup from does the job.
strdup from <string.h> does the job :)
– Yekatandilburg
Jul 21 '15 at 2:31
strdup makes a duplicate and returns the pointer to the duplicate. In this case for char arrays, you are back to where you started with no work done
– JoshKisb
Mar 1 at 14:13
add a comment |
What I would use is
char *s = "abcd";
Most of us wouldn't, because it risks undefined behaviour. The above is only safe forconst char*.
– Toby Speight
Apr 8 '16 at 13:21
add a comment |
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f579734%2fassigning-strings-to-arrays-of-characters%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
9 Answers
9
active
oldest
votes
9 Answers
9
active
oldest
votes
active
oldest
votes
active
oldest
votes
When initializing an array, C allows you to fill it with values. So
char s[100] = "abcd";
is basically the same as
int s[3] = { 1, 2, 3 };
but it doesn't allow you to do the assignment since s is an array and not a free pointer. The meaning of
s = "abcd"
is to assign the pointer value of abcd to s but you can't change s since then nothing will be pointing to the array.
This can and does work if s is a char* - a pointer that can point to anything.
If you want to copy the string simple use strcpy.
4
Good answer, except you should never use plain strcpy any longer. Use strncpy or strlcpy.
– dwc
Feb 23 '09 at 23:01
3
Also, s should be const char*, not char*.
– aib
Feb 24 '09 at 14:17
1
s[0] = 'x'; s[1] = 'y'; s[2] = 'z'; s[3] = 'm';works if one wants to replace the string characters one by one even after initialization.
– RBT
Oct 28 '16 at 2:44
@RBT, maybe it does in your platform with your compilation flags but often times these strings are defined in read-only memory. writing to it would cause a segfault or an Access-Violation error
– shoosh
Dec 4 '16 at 7:52
Why? Doingchar s[100]; s = "abcd";gives error makes perfect sense because s is effectively treated as a const pointer. So if we try assigning "abcd" in second line we are trying to change the value of the pointer which is not allowed. But if a const pointer is pointing to a memory location then the contents of the memory location should of course be modifiable. Let's sayspoints to memory location 1000 then s contains 1000 and memory location # 1000 contains a. I can't change s to store new memory location e.g. 2000 but I can store a new character e.g. z at memory location 1000.
– RBT
Dec 5 '16 at 3:46
|
show 2 more comments
When initializing an array, C allows you to fill it with values. So
char s[100] = "abcd";
is basically the same as
int s[3] = { 1, 2, 3 };
but it doesn't allow you to do the assignment since s is an array and not a free pointer. The meaning of
s = "abcd"
is to assign the pointer value of abcd to s but you can't change s since then nothing will be pointing to the array.
This can and does work if s is a char* - a pointer that can point to anything.
If you want to copy the string simple use strcpy.
4
Good answer, except you should never use plain strcpy any longer. Use strncpy or strlcpy.
– dwc
Feb 23 '09 at 23:01
3
Also, s should be const char*, not char*.
– aib
Feb 24 '09 at 14:17
1
s[0] = 'x'; s[1] = 'y'; s[2] = 'z'; s[3] = 'm';works if one wants to replace the string characters one by one even after initialization.
– RBT
Oct 28 '16 at 2:44
@RBT, maybe it does in your platform with your compilation flags but often times these strings are defined in read-only memory. writing to it would cause a segfault or an Access-Violation error
– shoosh
Dec 4 '16 at 7:52
Why? Doingchar s[100]; s = "abcd";gives error makes perfect sense because s is effectively treated as a const pointer. So if we try assigning "abcd" in second line we are trying to change the value of the pointer which is not allowed. But if a const pointer is pointing to a memory location then the contents of the memory location should of course be modifiable. Let's sayspoints to memory location 1000 then s contains 1000 and memory location # 1000 contains a. I can't change s to store new memory location e.g. 2000 but I can store a new character e.g. z at memory location 1000.
– RBT
Dec 5 '16 at 3:46
|
show 2 more comments
When initializing an array, C allows you to fill it with values. So
char s[100] = "abcd";
is basically the same as
int s[3] = { 1, 2, 3 };
but it doesn't allow you to do the assignment since s is an array and not a free pointer. The meaning of
s = "abcd"
is to assign the pointer value of abcd to s but you can't change s since then nothing will be pointing to the array.
This can and does work if s is a char* - a pointer that can point to anything.
If you want to copy the string simple use strcpy.
When initializing an array, C allows you to fill it with values. So
char s[100] = "abcd";
is basically the same as
int s[3] = { 1, 2, 3 };
but it doesn't allow you to do the assignment since s is an array and not a free pointer. The meaning of
s = "abcd"
is to assign the pointer value of abcd to s but you can't change s since then nothing will be pointing to the array.
This can and does work if s is a char* - a pointer that can point to anything.
If you want to copy the string simple use strcpy.
edited Jan 3 at 19:53
Francesco Boi
2,77022643
2,77022643
answered Feb 23 '09 at 22:54
shooshshoosh
49.1k44180295
49.1k44180295
4
Good answer, except you should never use plain strcpy any longer. Use strncpy or strlcpy.
– dwc
Feb 23 '09 at 23:01
3
Also, s should be const char*, not char*.
– aib
Feb 24 '09 at 14:17
1
s[0] = 'x'; s[1] = 'y'; s[2] = 'z'; s[3] = 'm';works if one wants to replace the string characters one by one even after initialization.
– RBT
Oct 28 '16 at 2:44
@RBT, maybe it does in your platform with your compilation flags but often times these strings are defined in read-only memory. writing to it would cause a segfault or an Access-Violation error
– shoosh
Dec 4 '16 at 7:52
Why? Doingchar s[100]; s = "abcd";gives error makes perfect sense because s is effectively treated as a const pointer. So if we try assigning "abcd" in second line we are trying to change the value of the pointer which is not allowed. But if a const pointer is pointing to a memory location then the contents of the memory location should of course be modifiable. Let's sayspoints to memory location 1000 then s contains 1000 and memory location # 1000 contains a. I can't change s to store new memory location e.g. 2000 but I can store a new character e.g. z at memory location 1000.
– RBT
Dec 5 '16 at 3:46
|
show 2 more comments
4
Good answer, except you should never use plain strcpy any longer. Use strncpy or strlcpy.
– dwc
Feb 23 '09 at 23:01
3
Also, s should be const char*, not char*.
– aib
Feb 24 '09 at 14:17
1
s[0] = 'x'; s[1] = 'y'; s[2] = 'z'; s[3] = 'm';works if one wants to replace the string characters one by one even after initialization.
– RBT
Oct 28 '16 at 2:44
@RBT, maybe it does in your platform with your compilation flags but often times these strings are defined in read-only memory. writing to it would cause a segfault or an Access-Violation error
– shoosh
Dec 4 '16 at 7:52
Why? Doingchar s[100]; s = "abcd";gives error makes perfect sense because s is effectively treated as a const pointer. So if we try assigning "abcd" in second line we are trying to change the value of the pointer which is not allowed. But if a const pointer is pointing to a memory location then the contents of the memory location should of course be modifiable. Let's sayspoints to memory location 1000 then s contains 1000 and memory location # 1000 contains a. I can't change s to store new memory location e.g. 2000 but I can store a new character e.g. z at memory location 1000.
– RBT
Dec 5 '16 at 3:46
4
4
Good answer, except you should never use plain strcpy any longer. Use strncpy or strlcpy.
– dwc
Feb 23 '09 at 23:01
Good answer, except you should never use plain strcpy any longer. Use strncpy or strlcpy.
– dwc
Feb 23 '09 at 23:01
3
3
Also, s should be const char*, not char*.
– aib
Feb 24 '09 at 14:17
Also, s should be const char*, not char*.
– aib
Feb 24 '09 at 14:17
1
1
s[0] = 'x'; s[1] = 'y'; s[2] = 'z'; s[3] = 'm'; works if one wants to replace the string characters one by one even after initialization.– RBT
Oct 28 '16 at 2:44
s[0] = 'x'; s[1] = 'y'; s[2] = 'z'; s[3] = 'm'; works if one wants to replace the string characters one by one even after initialization.– RBT
Oct 28 '16 at 2:44
@RBT, maybe it does in your platform with your compilation flags but often times these strings are defined in read-only memory. writing to it would cause a segfault or an Access-Violation error
– shoosh
Dec 4 '16 at 7:52
@RBT, maybe it does in your platform with your compilation flags but often times these strings are defined in read-only memory. writing to it would cause a segfault or an Access-Violation error
– shoosh
Dec 4 '16 at 7:52
Why? Doing
char s[100]; s = "abcd"; gives error makes perfect sense because s is effectively treated as a const pointer. So if we try assigning "abcd" in second line we are trying to change the value of the pointer which is not allowed. But if a const pointer is pointing to a memory location then the contents of the memory location should of course be modifiable. Let's say s points to memory location 1000 then s contains 1000 and memory location # 1000 contains a. I can't change s to store new memory location e.g. 2000 but I can store a new character e.g. z at memory location 1000.– RBT
Dec 5 '16 at 3:46
Why? Doing
char s[100]; s = "abcd"; gives error makes perfect sense because s is effectively treated as a const pointer. So if we try assigning "abcd" in second line we are trying to change the value of the pointer which is not allowed. But if a const pointer is pointing to a memory location then the contents of the memory location should of course be modifiable. Let's say s points to memory location 1000 then s contains 1000 and memory location # 1000 contains a. I can't change s to store new memory location e.g. 2000 but I can store a new character e.g. z at memory location 1000.– RBT
Dec 5 '16 at 3:46
|
show 2 more comments
There is no such thing as a "string" in C. In C, strings are one-dimensional array of char, terminated by a null character . Since you can't assign arrays in C, you can't assign strings either. The literal "hello" is syntactic sugar for const char x = {'h','e','l','l','o',''};
The correct way would be:
char s[100];
strncpy(s, "hello", 100);
or better yet:
#define STRMAX 100
char s[STRMAX];
size_t len;
len = strncpy(s, "hello", STRMAX);
2
Not the recommended approach. Beware of the oddities of strncpy: stackoverflow.com/a/1258577/2974922
– nucleon
Feb 23 '17 at 10:40
I think this approach could easily be recommended
– Volt
Oct 12 '18 at 8:00
add a comment |
There is no such thing as a "string" in C. In C, strings are one-dimensional array of char, terminated by a null character . Since you can't assign arrays in C, you can't assign strings either. The literal "hello" is syntactic sugar for const char x = {'h','e','l','l','o',''};
The correct way would be:
char s[100];
strncpy(s, "hello", 100);
or better yet:
#define STRMAX 100
char s[STRMAX];
size_t len;
len = strncpy(s, "hello", STRMAX);
2
Not the recommended approach. Beware of the oddities of strncpy: stackoverflow.com/a/1258577/2974922
– nucleon
Feb 23 '17 at 10:40
I think this approach could easily be recommended
– Volt
Oct 12 '18 at 8:00
add a comment |
There is no such thing as a "string" in C. In C, strings are one-dimensional array of char, terminated by a null character . Since you can't assign arrays in C, you can't assign strings either. The literal "hello" is syntactic sugar for const char x = {'h','e','l','l','o',''};
The correct way would be:
char s[100];
strncpy(s, "hello", 100);
or better yet:
#define STRMAX 100
char s[STRMAX];
size_t len;
len = strncpy(s, "hello", STRMAX);
There is no such thing as a "string" in C. In C, strings are one-dimensional array of char, terminated by a null character . Since you can't assign arrays in C, you can't assign strings either. The literal "hello" is syntactic sugar for const char x = {'h','e','l','l','o',''};
The correct way would be:
char s[100];
strncpy(s, "hello", 100);
or better yet:
#define STRMAX 100
char s[STRMAX];
size_t len;
len = strncpy(s, "hello", STRMAX);
edited Mar 17 at 4:35
H.S.
5,6291420
5,6291420
answered Feb 23 '09 at 22:52
dwcdwc
18.7k53752
18.7k53752
2
Not the recommended approach. Beware of the oddities of strncpy: stackoverflow.com/a/1258577/2974922
– nucleon
Feb 23 '17 at 10:40
I think this approach could easily be recommended
– Volt
Oct 12 '18 at 8:00
add a comment |
2
Not the recommended approach. Beware of the oddities of strncpy: stackoverflow.com/a/1258577/2974922
– nucleon
Feb 23 '17 at 10:40
I think this approach could easily be recommended
– Volt
Oct 12 '18 at 8:00
2
2
Not the recommended approach. Beware of the oddities of strncpy: stackoverflow.com/a/1258577/2974922
– nucleon
Feb 23 '17 at 10:40
Not the recommended approach. Beware of the oddities of strncpy: stackoverflow.com/a/1258577/2974922
– nucleon
Feb 23 '17 at 10:40
I think this approach could easily be recommended
– Volt
Oct 12 '18 at 8:00
I think this approach could easily be recommended
– Volt
Oct 12 '18 at 8:00
add a comment |
Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.
add a comment |
Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.
add a comment |
Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.
Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.
answered Feb 23 '09 at 22:49
SparrSparr
6,8242343
6,8242343
add a comment |
add a comment |
1 char s[100];
2 s = "hello";
In the example you provided, s is actually initialized at line 1, not line 2. Even though you didn't assign it a value explicitly at this point, the compiler did. At line 2, you're performing an assignment operation, and you cannot assign one array of characters to another array of characters like this. You'll have to use strcpy() or some kind of loop to assign each element of the array.
add a comment |
1 char s[100];
2 s = "hello";
In the example you provided, s is actually initialized at line 1, not line 2. Even though you didn't assign it a value explicitly at this point, the compiler did. At line 2, you're performing an assignment operation, and you cannot assign one array of characters to another array of characters like this. You'll have to use strcpy() or some kind of loop to assign each element of the array.
add a comment |
1 char s[100];
2 s = "hello";
In the example you provided, s is actually initialized at line 1, not line 2. Even though you didn't assign it a value explicitly at this point, the compiler did. At line 2, you're performing an assignment operation, and you cannot assign one array of characters to another array of characters like this. You'll have to use strcpy() or some kind of loop to assign each element of the array.
1 char s[100];
2 s = "hello";
In the example you provided, s is actually initialized at line 1, not line 2. Even though you didn't assign it a value explicitly at this point, the compiler did. At line 2, you're performing an assignment operation, and you cannot assign one array of characters to another array of characters like this. You'll have to use strcpy() or some kind of loop to assign each element of the array.
answered Feb 23 '09 at 22:57
Matt DavisMatt Davis
38.1k1579112
38.1k1579112
add a comment |
add a comment |
To expand on Sparr's answer
Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.
Think of it like this:
Imagine that there are 2 functions, called InitializeObject, and AssignObject. When the compiler sees thing = value, it looks at the context and calls one InitializeObject if you're making a new thing. If you're not, it instead calls AssignObject.
Normally this is fine as InitializeObject and AssignObject usually behave the same way. Except when dealing with char arrays (and a few other edge cases) in which case they behave differently. Why do this? Well that's a whole other post involving the stack vs the heap and so on and so forth.
PS: As an aside, thinking of it in this way will also help you understand copy constructors and other such things if you ever venture into C++
add a comment |
To expand on Sparr's answer
Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.
Think of it like this:
Imagine that there are 2 functions, called InitializeObject, and AssignObject. When the compiler sees thing = value, it looks at the context and calls one InitializeObject if you're making a new thing. If you're not, it instead calls AssignObject.
Normally this is fine as InitializeObject and AssignObject usually behave the same way. Except when dealing with char arrays (and a few other edge cases) in which case they behave differently. Why do this? Well that's a whole other post involving the stack vs the heap and so on and so forth.
PS: As an aside, thinking of it in this way will also help you understand copy constructors and other such things if you ever venture into C++
add a comment |
To expand on Sparr's answer
Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.
Think of it like this:
Imagine that there are 2 functions, called InitializeObject, and AssignObject. When the compiler sees thing = value, it looks at the context and calls one InitializeObject if you're making a new thing. If you're not, it instead calls AssignObject.
Normally this is fine as InitializeObject and AssignObject usually behave the same way. Except when dealing with char arrays (and a few other edge cases) in which case they behave differently. Why do this? Well that's a whole other post involving the stack vs the heap and so on and so forth.
PS: As an aside, thinking of it in this way will also help you understand copy constructors and other such things if you ever venture into C++
To expand on Sparr's answer
Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.
Think of it like this:
Imagine that there are 2 functions, called InitializeObject, and AssignObject. When the compiler sees thing = value, it looks at the context and calls one InitializeObject if you're making a new thing. If you're not, it instead calls AssignObject.
Normally this is fine as InitializeObject and AssignObject usually behave the same way. Except when dealing with char arrays (and a few other edge cases) in which case they behave differently. Why do this? Well that's a whole other post involving the stack vs the heap and so on and so forth.
PS: As an aside, thinking of it in this way will also help you understand copy constructors and other such things if you ever venture into C++
edited May 23 '17 at 11:47
Community♦
11
11
answered Feb 23 '09 at 22:59
Orion EdwardsOrion Edwards
86k51195275
86k51195275
add a comment |
add a comment |
Note that you can still do:
s[0] = 'h';
s[1] = 'e';
s[2] = 'l';
s[3] = 'l';
s[4] = 'o';
s[5] = '';
It's much nicer and easier to use strncpy(), even though I'm pretty sure strncpy() does exactly this internally.
– Chris Lutz
Feb 24 '09 at 14:33
Of course. But this is as close as it gets to 's = "hello";' In fact, this should have been implemented in C, seeing as how you can assign structs.
– aib
Feb 24 '09 at 14:47
I mean, memberwise copy by assignment in structs but not in arrays doesn't make sense.
– aib
Feb 24 '09 at 14:49
add a comment |
Note that you can still do:
s[0] = 'h';
s[1] = 'e';
s[2] = 'l';
s[3] = 'l';
s[4] = 'o';
s[5] = '';
It's much nicer and easier to use strncpy(), even though I'm pretty sure strncpy() does exactly this internally.
– Chris Lutz
Feb 24 '09 at 14:33
Of course. But this is as close as it gets to 's = "hello";' In fact, this should have been implemented in C, seeing as how you can assign structs.
– aib
Feb 24 '09 at 14:47
I mean, memberwise copy by assignment in structs but not in arrays doesn't make sense.
– aib
Feb 24 '09 at 14:49
add a comment |
Note that you can still do:
s[0] = 'h';
s[1] = 'e';
s[2] = 'l';
s[3] = 'l';
s[4] = 'o';
s[5] = '';
Note that you can still do:
s[0] = 'h';
s[1] = 'e';
s[2] = 'l';
s[3] = 'l';
s[4] = 'o';
s[5] = '';
answered Feb 24 '09 at 14:22
aibaib
34.1k106374
34.1k106374
It's much nicer and easier to use strncpy(), even though I'm pretty sure strncpy() does exactly this internally.
– Chris Lutz
Feb 24 '09 at 14:33
Of course. But this is as close as it gets to 's = "hello";' In fact, this should have been implemented in C, seeing as how you can assign structs.
– aib
Feb 24 '09 at 14:47
I mean, memberwise copy by assignment in structs but not in arrays doesn't make sense.
– aib
Feb 24 '09 at 14:49
add a comment |
It's much nicer and easier to use strncpy(), even though I'm pretty sure strncpy() does exactly this internally.
– Chris Lutz
Feb 24 '09 at 14:33
Of course. But this is as close as it gets to 's = "hello";' In fact, this should have been implemented in C, seeing as how you can assign structs.
– aib
Feb 24 '09 at 14:47
I mean, memberwise copy by assignment in structs but not in arrays doesn't make sense.
– aib
Feb 24 '09 at 14:49
It's much nicer and easier to use strncpy(), even though I'm pretty sure strncpy() does exactly this internally.
– Chris Lutz
Feb 24 '09 at 14:33
It's much nicer and easier to use strncpy(), even though I'm pretty sure strncpy() does exactly this internally.
– Chris Lutz
Feb 24 '09 at 14:33
Of course. But this is as close as it gets to 's = "hello";' In fact, this should have been implemented in C, seeing as how you can assign structs.
– aib
Feb 24 '09 at 14:47
Of course. But this is as close as it gets to 's = "hello";' In fact, this should have been implemented in C, seeing as how you can assign structs.
– aib
Feb 24 '09 at 14:47
I mean, memberwise copy by assignment in structs but not in arrays doesn't make sense.
– aib
Feb 24 '09 at 14:49
I mean, memberwise copy by assignment in structs but not in arrays doesn't make sense.
– aib
Feb 24 '09 at 14:49
add a comment |
I know that this has already been answered, but I wanted to share an answer that I gave to someone who asked a very similar question on a C/C++ Facebook group.
Arrays don't have assignment operator functions*. This means that you cannot simply assign a char array to a string literal. Why? Because the array itself doesn't have any assignment operator. (*It's a const pointer which can't be changed.)
arrays are simply an area of contiguous allocated memory and the name
of the array is actually a pointer to the first element of the array.
(Quote from https://www.quora.com/Can-we-copy-an-array-using-an-assignment-operator)
To copy a string literal (such as "Hello world" or "abcd") to your char array, you must manually copy all char elements of the string literal onto the array.
char s[100]; This will initialize an empty array of length 100.
Now to copy your string literal onto this array, use strcpy
strcpy(s, "abcd"); This will copy the contents from the string literal "abcd" and copy it to the s[100] array.
Here's a great example of what it's doing:
int i = 0; //start at 0
do {
s[i] = ("Hello World")[i]; //assign s[i] to the string literal index i
} while(s[i++]); //continue the loop until the last char is null
You should obviously use strcpy instead of this custom string literal copier, but it's a good example that explains how strcpy fundamentally works.
Hope this helps!
add a comment |
I know that this has already been answered, but I wanted to share an answer that I gave to someone who asked a very similar question on a C/C++ Facebook group.
Arrays don't have assignment operator functions*. This means that you cannot simply assign a char array to a string literal. Why? Because the array itself doesn't have any assignment operator. (*It's a const pointer which can't be changed.)
arrays are simply an area of contiguous allocated memory and the name
of the array is actually a pointer to the first element of the array.
(Quote from https://www.quora.com/Can-we-copy-an-array-using-an-assignment-operator)
To copy a string literal (such as "Hello world" or "abcd") to your char array, you must manually copy all char elements of the string literal onto the array.
char s[100]; This will initialize an empty array of length 100.
Now to copy your string literal onto this array, use strcpy
strcpy(s, "abcd"); This will copy the contents from the string literal "abcd" and copy it to the s[100] array.
Here's a great example of what it's doing:
int i = 0; //start at 0
do {
s[i] = ("Hello World")[i]; //assign s[i] to the string literal index i
} while(s[i++]); //continue the loop until the last char is null
You should obviously use strcpy instead of this custom string literal copier, but it's a good example that explains how strcpy fundamentally works.
Hope this helps!
add a comment |
I know that this has already been answered, but I wanted to share an answer that I gave to someone who asked a very similar question on a C/C++ Facebook group.
Arrays don't have assignment operator functions*. This means that you cannot simply assign a char array to a string literal. Why? Because the array itself doesn't have any assignment operator. (*It's a const pointer which can't be changed.)
arrays are simply an area of contiguous allocated memory and the name
of the array is actually a pointer to the first element of the array.
(Quote from https://www.quora.com/Can-we-copy-an-array-using-an-assignment-operator)
To copy a string literal (such as "Hello world" or "abcd") to your char array, you must manually copy all char elements of the string literal onto the array.
char s[100]; This will initialize an empty array of length 100.
Now to copy your string literal onto this array, use strcpy
strcpy(s, "abcd"); This will copy the contents from the string literal "abcd" and copy it to the s[100] array.
Here's a great example of what it's doing:
int i = 0; //start at 0
do {
s[i] = ("Hello World")[i]; //assign s[i] to the string literal index i
} while(s[i++]); //continue the loop until the last char is null
You should obviously use strcpy instead of this custom string literal copier, but it's a good example that explains how strcpy fundamentally works.
Hope this helps!
I know that this has already been answered, but I wanted to share an answer that I gave to someone who asked a very similar question on a C/C++ Facebook group.
Arrays don't have assignment operator functions*. This means that you cannot simply assign a char array to a string literal. Why? Because the array itself doesn't have any assignment operator. (*It's a const pointer which can't be changed.)
arrays are simply an area of contiguous allocated memory and the name
of the array is actually a pointer to the first element of the array.
(Quote from https://www.quora.com/Can-we-copy-an-array-using-an-assignment-operator)
To copy a string literal (such as "Hello world" or "abcd") to your char array, you must manually copy all char elements of the string literal onto the array.
char s[100]; This will initialize an empty array of length 100.
Now to copy your string literal onto this array, use strcpy
strcpy(s, "abcd"); This will copy the contents from the string literal "abcd" and copy it to the s[100] array.
Here's a great example of what it's doing:
int i = 0; //start at 0
do {
s[i] = ("Hello World")[i]; //assign s[i] to the string literal index i
} while(s[i++]); //continue the loop until the last char is null
You should obviously use strcpy instead of this custom string literal copier, but it's a good example that explains how strcpy fundamentally works.
Hope this helps!
edited Mar 1 at 15:49
answered Mar 1 at 15:44
JMS CreatorJMS Creator
214
214
add a comment |
add a comment |
You can use this:
yylval.sval=strdup("VHDL + Volcal trance...");
Where
yylval is char*. strdup from does the job.
strdup from <string.h> does the job :)
– Yekatandilburg
Jul 21 '15 at 2:31
strdup makes a duplicate and returns the pointer to the duplicate. In this case for char arrays, you are back to where you started with no work done
– JoshKisb
Mar 1 at 14:13
add a comment |
You can use this:
yylval.sval=strdup("VHDL + Volcal trance...");
Where
yylval is char*. strdup from does the job.
strdup from <string.h> does the job :)
– Yekatandilburg
Jul 21 '15 at 2:31
strdup makes a duplicate and returns the pointer to the duplicate. In this case for char arrays, you are back to where you started with no work done
– JoshKisb
Mar 1 at 14:13
add a comment |
You can use this:
yylval.sval=strdup("VHDL + Volcal trance...");
Where
yylval is char*. strdup from does the job.
You can use this:
yylval.sval=strdup("VHDL + Volcal trance...");
Where
yylval is char*. strdup from does the job.
edited Jul 21 '15 at 2:39
josliber♦
37.6k1165104
37.6k1165104
answered Jul 21 '15 at 2:30
YekatandilburgYekatandilburg
16112
16112
strdup from <string.h> does the job :)
– Yekatandilburg
Jul 21 '15 at 2:31
strdup makes a duplicate and returns the pointer to the duplicate. In this case for char arrays, you are back to where you started with no work done
– JoshKisb
Mar 1 at 14:13
add a comment |
strdup from <string.h> does the job :)
– Yekatandilburg
Jul 21 '15 at 2:31
strdup makes a duplicate and returns the pointer to the duplicate. In this case for char arrays, you are back to where you started with no work done
– JoshKisb
Mar 1 at 14:13
strdup from <string.h> does the job :)
– Yekatandilburg
Jul 21 '15 at 2:31
strdup from <string.h> does the job :)
– Yekatandilburg
Jul 21 '15 at 2:31
strdup makes a duplicate and returns the pointer to the duplicate. In this case for char arrays, you are back to where you started with no work done
– JoshKisb
Mar 1 at 14:13
strdup makes a duplicate and returns the pointer to the duplicate. In this case for char arrays, you are back to where you started with no work done
– JoshKisb
Mar 1 at 14:13
add a comment |
What I would use is
char *s = "abcd";
Most of us wouldn't, because it risks undefined behaviour. The above is only safe forconst char*.
– Toby Speight
Apr 8 '16 at 13:21
add a comment |
What I would use is
char *s = "abcd";
Most of us wouldn't, because it risks undefined behaviour. The above is only safe forconst char*.
– Toby Speight
Apr 8 '16 at 13:21
add a comment |
What I would use is
char *s = "abcd";
What I would use is
char *s = "abcd";
edited Apr 8 '16 at 13:23
Toby Speight
17.4k134368
17.4k134368
answered Oct 8 '12 at 20:27
VivekVivek
332
332
Most of us wouldn't, because it risks undefined behaviour. The above is only safe forconst char*.
– Toby Speight
Apr 8 '16 at 13:21
add a comment |
Most of us wouldn't, because it risks undefined behaviour. The above is only safe forconst char*.
– Toby Speight
Apr 8 '16 at 13:21
Most of us wouldn't, because it risks undefined behaviour. The above is only safe for
const char*.– Toby Speight
Apr 8 '16 at 13:21
Most of us wouldn't, because it risks undefined behaviour. The above is only safe for
const char*.– Toby Speight
Apr 8 '16 at 13:21
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f579734%2fassigning-strings-to-arrays-of-characters%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
