I have defined c as
char c[][10]
in function definition and used it like c[i]="gray";
Whats wrong? I searched on net, it shows the same syntax.
Thanks.
You cannot use assignment (=
) on an array. If you change c
to an array of pointers, that might work, depending on what you need to do with it.
const char *c[20];
c[i] = "gray";
Or if the declared type must be array of arrays, you could use strncpy
:
char c[20][10];
strncpy(c[i], "gray", sizeof(c[i]));
The problem is that arrays are not assignable in C. String constants like "gray"
are character array constants: in this case, the type is char[5]
(4 + 1 for the terminating null).
If you know that the destination array is large enough to hold the desired string, you can use strcpy
to copy the string like so:
// Make sure you know that c[i] is big enough!
strcpy(c[i], "gray");
A better idea is to use a safer function such as strlcpy
(BSD-based systems and Mac OS X) or strcpy_s
(Windows):
strlcpy(c[i], "gray", 10); // 10 is the size of c[i]
However, these functions are platform-specific and not all that portable. You could also roll your own implementation if speed is not an issue:
size_t strlcpy(char *dst, const char *src, size_t size)
{
size_t len = 0;
while(size > 1 && *src)
{
*dst++ = *src++;
size--;
len++;
}
if(size > 0)
*dst = 0;
return len + strlen(src);
}
Do not use strncpy
, since it could potentially leave you with a non-null-terminated string
this code will work and make the correct assignements in 3 different ways:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string myString = "hello my friends from Brazil";
char charOut[myString.size()];
strncpy(charOut, myString.c_str(), myString.size());
std::cout << "Char by strncpy string var " << charOut << std::endl;
const char *charOut2;
charOut2 = "sup my homies in L.A.";
std::cout << "Char by const " << charOut2 << std::endl;
string myString2 = "hallo mein bruder in Berlin";
char charOut3[myString2.size()];
strcpy(charOut3, myString2.c_str());
std::cout << "Char by strcpy string var " << charOut3 << std::endl;
}
runs ok on ubuntu servers. did not test on other systems.
Try using strcpy()
(found in the cstring
header) instead of just plain assignment.