0

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..?

3
  • int size = sizeof(**str); -- the value of size will always be 1 since str is a char **, the double dereference results in a char, and sizeof char is guaranteed to be 1 always. Commented Aug 26, 2018 at 23:55
  • @DavidBowling: True, but not a problem. Commented Aug 26, 2018 at 23:56
  • 1
    Consider what happens when the first character is a ','. *str[i] = '\0'; attempts to assigned via an uninitialized pointer. Commented Aug 27, 2018 at 2:14

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.