Why, when I add commented code, does it crash?

#include <stdio.h> char string[100]; int i = 0; void read(char *p){ p = &string[i]; while((string[i] = getchar()) != '\n') i++; string[i++] = '\0'; } int main(){ char *line[10]; int i; for(i = 0; i < 3; i++) read(line[i]); /* for(i = 0; i < 3; i++) printf("%s\n", line[i]); */ return 0; } 
  • one
    because line [i] is not initialized. at least assign them to the return value, or pass a pointer to a pointer in read() . In general, it would be good to allocate memory for them in a heap ... and 5-10 more problems in the code for which there is not enough comment. - Fat-Zer

1 answer 1

line in the context of this code is an array of 10 lines, that is, pointers to characters (I call characters type char ); to reduce confusion, I will call these pointers values. As I understand your code, you want in the read function to change this value in the line array. However, your code changes only the value of the variable p inside the function, and the line array itself remains uninitialized as a result. To change the value in the line array itself, you need to pass a pointer to a value (that is, a pointer to a pointer) and in the function change the value of the pointer. The code below works:

 #include <stdio.h> char string[100]; int i = 0; void read(char **p){ /* Меняем значение не в переменной внутри функции, */ /* а в том месте, куда указывает указатель */ *p = &string[i]; while((string[i] = getchar()) != '\n') i++; string[i++] = '\0'; } int main(){ char *line[3]; int i; for(i = 0; i < 3; i++) read(&line[i]); /* Передаём указатель на значение массива */ for(i = 0; i < 3; i++) printf("%s\n", line[i]); return 0; } 

In addition to this, there are other problems in the code: for example, your string contains only one hundred characters, so an attempt to read more than one hundred characters can lead to unspecified behavior, in particular to a crash. And your code blocks are poorly designed, which can confuse the reader. But this is not the topic of the question, and I hope you understand all this yourself :)