0

For a homework assignment, we are working on CSV parser. I'm trying to get things working, but I've run into an issue. I can't seem to assign a value to "field" value in the struct. In the code they provided they have:

typedef char f_string[MAX_CHARS+1] ;    /* string for each field */

    typedef struct {
        int nfields;                        /* 0 => end of file */
        f_string field[MAX_FIELDS];         /* array of strings for fields */
    } csv_line ;

With the above constants defined at 20 and 15. Looking at what they have, the struct holds and int, and it holds an array that should be populated with the f_string typedef they defined earlier. Alright, cool. I tried to do it this way:

f_string test = "Hello, Bob";
f_string testAgain = "this is dumb, k?";
f_string anArray[MAX_FIELDS] = {*test, *testAgain};

csv_line aLine;
aLine.nfields = 3;
aLine.field = *anArray;

When I make "anArray", if I don't have the dereferences to test and testAgain, I get warnings about making integers to pointers without a cast. So I leave them in. But the line:

aLine.field = *anArray;

Returns the error: "csv.c:87: error: incompatible types in assignment" with or without the pointer there... so I'm not sure how I should be assigning that variable? Help would be appreciated!

1 Answer 1

5

You can't assign to an array using =. See this question for a more detailed explanation.

You'll need to copy each string using the strcpy (or the safer strncpy) function:

for (int i = 0; i < aLine.nfields; ++i)
{
  strncpy(aLine.field[i], anArray[i], MAX_CHARS);
}

Also, the test code you provide isn't going to do what you expect.

f_string test = "Hello, Bob";
f_string testAgain = "this is dumb, k?";
f_string anArray[MAX_FIELDS] = {*test, *testAgain};

This will copy the first character of test and testAgain. You need to do something like:

f_string test = "Hello, Bob";
f_string testAgain = "this is dumb, k?";
f_string anArray[MAX_FIELDS];
strcpy(anArray[0], test);
strcpy(anArray[1], testAgain);

Or just:

f_string anArray[MAX_FIELDS] = {"Hello, Bob", "this is dumb, k"};
Sign up to request clarification or add additional context in comments.

2 Comments

Note that this won't necessarily null-terminate the string unless the array already has an '\0' at aLine.field[i][MAX_CHARS].
I realized that my code above wasn't working, and that with your code, I would have to strcpy them in. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.