6

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.

Ava
  • 5,783
  • 27
  • 58
  • 86

4 Answers4

17

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]));
aschepler
  • 70,891
  • 9
  • 107
  • 161
14

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

Community
  • 1
  • 1
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
1

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.

tony gil
  • 9,424
  • 6
  • 76
  • 100
1

Try using strcpy() (found in the cstring header) instead of just plain assignment.

jonsca
  • 10,218
  • 26
  • 54
  • 62