Reputation: 11
I'm trying to read in a value user input and store it in a string. The string must be all the characters before a comma or the end of the line, and it needs to output either the comma, or the EOF.
I'm trying to read each character in and allocate space in the string as needed but the file stops after reading the first input.
This is what I have so far:
char read_data(char** str) {
char c = 'n';
int size = sizeof(**str);
int i = 0;
while (((c = getchar()) != COMMA) && (c != NEWLINE)) {
size += sizeof(c);
*str = (char*) realloc(*str, size + 1);
assert(*str);
*str[i] = c;
i++;
}
*str[i] = '\0'; //terminator
return c;
}
int main(int argc, char const *argv[]) {
char* string = NULL;
char left;
left = read_data(&string);
printf("left: %c\n", left);
printf("string: %s\n", string);
free(string);
return 0;
}
I can't work out why it's breaking. Would anyone have any tips/ideas..?
Upvotes: 0
Views: 589
Reputation: 283684
Because array subscripting ([]
) has higher precedence than indirection (*
), when you write *str[i]
you get *(str[i])
-- the first character of the ith string. However, you wanted (*str)[i]
.
Here are four ways to write what you mean, all of which mean "the ith character of string *str
":
(*str)[i]
str[0][i]
i[*str]
*(*str+i)
Upvotes: 1