BLU
BLU

Reputation: 121

Questions about Strings in C

Im still new to C, and Im a bit confused on how to work with strings at the moment. right now I have two functions: get_field(), and get_line().

typedef char f_string[MAX_CHARS+1] ;
typedef struct {
        int nfields ;                        
        f_string field[MAX_FIELDS] ;            
} csv_line ;



csv_line get_line() {
        csv_line toBe;
        f_string sField;
        toBe.nfields = 0;
        int r;
        while(r != '\n'){
                r = get_field(sField);
                printf("sField: %d\n", *sField);
                //toBe.field += *sField;
                if(r != EOF){
                        toBe.nfields += 1;
                }
                //sField = *"";
        }
        return toBe;

}


int get_field(f_string field) {
        char ch;
        ch = getchar();
        while(is_end_of_field(ch) == 0){
                field += ch;
                ch = getchar();
        }
        field += '\0';
        return ch;

What I am trying to do with it is parse through a line from standard input until it gets to an end of field condition (either ',' '\n' or EOF) then take that string and add it to the "field" which I believe is an array of these fstrings. get_field() seems to run fine but when I try to print out the sField, which I believe is being edited from within get_field, I only get a 0. What am I doing wrong here? MAX_FIELDS is set to 15 and MAX_CHARS is set to 20. The Errors I get when I try to compile with the currently commented out lines are...

error: invalid operands to binary + (have ‘char[15][21]’ and ‘int’)
error: incompatible types when assigning to type ‘f_string’ from type ‘char’

Upvotes: 0

Views: 163

Answers (1)

Lee Duhem
Lee Duhem

Reputation: 15121

  1. You are using r before you initialized it at while(r != '\n'){

  2. toBe.field += *sField; should be replaced by something like strcpy(toBe.field[i], sField);

  3. field += ch; should be replaced by something like field[i] = ch;, because in get_field() field is a pointer to char; field += '\0'; should be fixed similarly.

By the way, there are many potential buffer overflow problems in your code, you may also want to fix them.

Upvotes: 2

Related Questions