Assigning strings to arrays of characters
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
.
How to assign a string to a char array without sprintf or strcpy
Given two strings and a buffer big enough to hold both, you can use a loop to copy the content:
const char *s1 = "Hello";
const char *s2 = "World";
char s[12];
int i;
for(i = 0; i < 5; i++) {
s[i] = s1[i];
}
s[i++] = ' ';
for(i = 0; i < 5; i++) {
s[i + 6] = s2[i];
}
s[i + 6] = '\0';
If it's a case like command line arguments, where you have an array of pointers with a count, you can use a pair of nested loops for the whole thing:
char *argv[] = {
"Hello",
"World",
NULL
};
int argc = 2;
char s[12];
int i, j, k;
j = 0;
for(k = 0; k < argc; k++) {
for(i = 0; argv[k][i]; i++) {
s[j++] = argv[k][i];
}
s[j++] = ' ';
}
if(k) {
s[--j] = '\0';
} else {
s[0] = '\0';
}
Assigning a string of characters to a char array
Strictly speaking, an array is not a pointer! And an array ( base address of the array ) cant be a modifiable lvalue. ie it cannot appear on the left hand side of an assignment operator.Arrays decay into pointers only in certain circumstances. Read this SO post to learn when arrays decay into pointers. Here is one more nice article which explains the differences between arrays and pointers
Also read about lvalues and rvalues here so that you get an idea of things which cannot appear on the LHS of =
char a[10]="iqbal"; // it works
In this case, internally what happens is
a[0] = 'i';
a[1] = 'q';
.
.
a[5] = '\0';
So everything is fine as array[i]
is a modifiable lvalue.
a="iqbal"; // does not work
Internally, this is roughly equivalent to
0x60000(Address of a, but is a simple number here ) = Address of "iqbal"
This is wrong as we cannot assign something to a number.
In C, why can't I assign a string to a char array after it's declared?
Arrays are second-class citizens in C, they do not support assignment.
char x[] = "This is initialization, not assignment, thus ok.";
This does not work:
x = "Compilation-error here, tried to assign to an array.";
Use library-functions or manually copy every element for itself:
#include <string.h>
strcpy(x, "The library-solution to string-assignment.");
How to assign a new string to char array without string functions
In C, a string is just an array of type char
that contains printable characters followed by a terminating null character ('\0'
).
With this knowledge, you can eschew the standard functions strcpy
and strcat
and assign a string manually:
A[0] = '1';
A[1] = '2';
A[2] = '\0';
If there were characters in the string A
beyond index 2
, they don't matter since string processing functions will stop reading the string once they encounter the null terminator at A[2]
.
Assigning direct string to char array in C
Because, an array type is not a modifiable lvalue, hence cannot be "assigned".
An assignment operator needs a modifiable lvalue as the LHS operand.
Related, quoting C11
, chapter §6.5.16
An assignment operator shall have a modifiable lvalue as its left operand.
and, chapter §6.3.2.1
[....] A modifiable lvalue is an lvalue that
does not have array type, does not have an incomplete type, does not have a constqualified
type, and if it is a structure or union, does not have any member (including,
recursively, any member or element of all contained aggregates or unions) with a constqualified
type.
In your case, for an array defined like
char name[5][10];
the element name[0]
is of type char [10]
, that is, an array of 10 char
s.
Assign string values to char array in reversed order with for loop
Copying the whole string including the null-terminator like this is correct since C++11 (before, accessing str[str.size()]
would be undefined behavior). However, you also include that null terminator when you reverse the string. So as a result, the null terminator is the first character in your reversed string. This means that the string will be considered empty.
Instead, I would change the loop to this:
for (int i = 0; i < str.length(); i++) { // < instead of <=
input[i] = str[i];
reversed[i] = str[str.length() - i - 1]; // note the -1
}
Which copies the strings without the null terminator, and then you can set those manually:
input[str.length()] = '\0';
reversed[str.length()] = '\0';
Also, since the char
array needs to hold the null-terminaror, its length should be str.length()+1
.
On a side node, char input[str.length()];
is a so-called Variable-length array, which is not part of C++, but some compilers allow it nevertheless. It might not work if you compile the program using a different compiler.
Related Topics
Which MACro to Wrap MAC Os X Specific Code in C/C++
Proper Way of Casting Pointer Types
Can Templates Be Used to Access Struct Variables by Name
Llvm Get Constant Integer Back from Value*
C++ Cannot Convert from Base a to Derived Type B via Virtual Base A
Function Template with an Operator
Cannot Use .Begin() or .End() on an Array
Treat C Cstyle Array as Std::Array
C++ Object Instantiation VS Assignment
Recognize Open and Closed Shapes Opencv
Conversion from Iplimage* to Cv::Mat
How to Force Gcc to Link Unreferenced, Static C++ Objects from a Library
C++ Nested Classes Accessibility
How to Write a Variadic Template Recursive Function
Purpose of Explicit Default Constructors
This Case of Template Function Overloading Eludes My Understanding