locked
Problem to assign values RRS feed

  • Question

  • Hi,
    I declare these
    struct nameval
    {
        char fld_nm[30];
        float fld_val;
    };

    int main()
    {
        std::vector<nameval> records;
        ...
        
    but I get these errors

    1>c:\App15\App15\App15.cpp(26): error C2440: '=' : cannot convert from 'const char [3]' to 'char [30]'
    1>          There is no context in which this conversion is possible
    1>c:\App15\App15\App15.cpp(27

    due to the last 2 lines below
        for (cnt=0;cnt<1000;cnt++)
        {
            nameval val;
            val.fld_nm="ab";
            val.fld_val=cnt;
            ...
    why?

    Many Thanks & Best Regards, Hua Min

    Friday, September 13, 2013 4:26 AM

Answers

  • fld_nm is not a pointer, is an array. You can't assign a value to an array but you can copy data into it. In this case you need to use strcpy:

    strcpy(val.fld_nam, "ab");

    • Marked as answer by Jackson_1990 Friday, September 13, 2013 6:22 AM
    Friday, September 13, 2013 6:03 AM

All replies

  • fld_nm is not a pointer, is an array. You can't assign a value to an array but you can copy data into it. In this case you need to use strcpy:

    strcpy(val.fld_nam, "ab");

    • Marked as answer by Jackson_1990 Friday, September 13, 2013 6:22 AM
    Friday, September 13, 2013 6:03 AM
  • struct nameval
    {
        char fld_nm[30];
        float fld_val;
    };

            nameval val;
            val.fld_nm="ab";

    You should know by now that you can't *assign* a value to a C-style string or char array
    using the assignment operator. You have to use one of the str* functions such as
    strcpy(), or memcpy(), etc.

    e.g. - strcpy(val.fld_nm, "ab");

    Or use a std::string so you *can* use the assignment operator.

    - Wayne

    Friday, September 13, 2013 6:06 AM