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..?
int size = sizeof(**str);-- the value ofsizewill always be 1 sincestris achar **, the double dereference results in achar, andsizeof charis guaranteed to be 1 always.','.*str[i] = '\0';attempts to assigned via an uninitialized pointer.