Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error:incompatible types in assignment of 'const char[5]' to 'char[10]'

Tags:

c++

char

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.

like image 863
Ava Avatar asked Mar 24 '11 02:03

Ava


2 Answers

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]));
like image 198
aschepler Avatar answered Nov 15 '22 08:11

aschepler


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

like image 39
Adam Rosenfield Avatar answered Nov 15 '22 07:11

Adam Rosenfield