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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With