0

I have an array of pointers to chars where I store string from the console. How can I check, if a new string is entered to inkrement the index? I thought about something like that but I always get Segmentation Fault.

char** arr;
int i = 0;
int j = 0;

arr = malloc(sizeof(char*) * 10);

while (arr[i][j] != '\n') {
    scanf("%c", &arr[i][j]);
    j++;
}
i++;
// Read next string here
2
  • My code doesnt work, it seems like after entering a string it just continues to execute the while loop a few times and then asks for a new string. How can I do this, I wanna store a string from the console in the array and each \n represents that now comes a new string. Any ideas? Commented Dec 5, 2014 at 20:30
  • you allocated memory for an array of 10 pointers to char. You also need to allocate memory for each of those pointers. And you probably should initialize the first allocation to all NULL. before reading any strings. as it is, [j] is an offset into unallocated memory Commented Dec 6, 2014 at 0:55

3 Answers 3

2

You are allocating memory for the pointers. Similarly you need to make those pointers point to some memory location before writing something to it.Like

arr[i] = malloc(sizeof(char) *20);
Sign up to request clarification or add additional context in comments.

Comments

0

You only have allocated memory for *arr, but not yet for **arr. arr now points to memory that can store 10 char pointers, but where are these char pointers pointing to? To 'nothing' yet, so you first have to let them point to memory before you can dereference them via arr[i][j]

Comments

0

I think you either need to malloc the j's as well, or use a 2-dimentional array and [i*j_size+j] to index. Also, scanf can read strings with %s.

See also http://rosettacode.org/wiki/User_input/Text#C (and other examples on rosetta code).

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.