Assigning Array to a Struct value in C
For a homework assignment, we are working on CSV parser. I'm trying to get thi开发者_运维技巧ngs 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!
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"};
精彩评论