Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning strings to arrays of characters

Tags:

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?

like image 698
Ree Avatar asked Feb 23 '09 22:02

Ree


People also ask

Can you assign a char array to a string?

Use the overloaded '=' operator to assign the characters in the character array to the string.

Can strings be treated as arrays of characters?

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.

How do you assign a character array?

Initializing Char Array A char array can be initialized by conferring to it a default size. char [] JavaCharArray = new char [ 4 ]; This assigns to it an instance with size 4.

Can we assign a string to char array in C?

The c_str() and strcpy() function in C++C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0').


2 Answers

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.

like image 173
shoosh Avatar answered Oct 13 '22 12:10

shoosh


There is no such thing as a "string" in C. In C, strings are one-dimensional array of char, terminated by a null character \0. 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','\0'};

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); 
like image 22
dwc Avatar answered Oct 13 '22 13:10

dwc