LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   c program to read a line and store it in a array (http://www.linuxquestions.org/questions/programming-9/c-program-to-read-a-line-and-store-it-in-a-array-4175448757/)

batman4 02-05-2013 04:04 PM

c program to read a line and store it in a array
 
please explain me why i am getting segmentation fault in my program.

Code:

#include<stdio.h>
#define max 10000
main(){
int i ,c ;
char s[max];

for(i=0 ;i<max-1 && (c=getchar())!= EOF && c!= '\n'; i++){
s[i] =c;

printf("%s" , s[i]);
}

}


mina86 02-05-2013 04:20 PM

Code:

$ gcc test.c
test.c: In function ‘main’:
test.c:10:1: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat]

Do you now know why? Enable all warnings in your compiler.

By the way, you are not terminating the string with a NUL byte.

Also, use correct indentation, proper prototype of main is int main(void), and it should return 0; at the end.

kedarp 02-05-2013 09:20 PM

You declared int c and using it to get a char value.

Code:

char c=getchar()
Second thing,
get printf() out of the for loop and pass it the base address.

Code:

printf("%s",s);

ntubski 02-05-2013 09:53 PM

Quote:

Originally Posted by kedarp (Post 4885185)
You declared int c and using it to get a char value.

getchar() returns an int value, EOF doesn't fit in a char.

H_TeXMeX_H 02-06-2013 02:49 AM

A C string is an array, so why not read a string using fscanf or fgets ?


All times are GMT -5. The time now is 02:47 AM.