-
strings
I am trying to read in a string from the command line, copy it to another and then print it out character by character in the following code. I get a segfault when I use 'exp[i]'. Any ideas why, and what I should do to fix it? Thanks!
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLENGTH 256
int main(int argc, char * argv[])
{
// read in char
char exp [MAXLENGTH];
int i=0;
if(argc<2)
{
printf("Try again using format ./a.out \"<expression>\"\n");
return 0;
}
strcpy(exp, argv[1])
while(exp[i]!='\0')
{
printf("Char=%s\t",exp[i]);
i++;
}
return 1;
}
-
Compile with your warnings turned all the way up:
Code:
$ gcc -Wall -g -o foo foo.c
foo.c: In function 'main':
foo.c:23: warning: format '%s' expects type 'char *', but argument 2 has type 'int'
Then, read the documentation for printf. %s is for strings (char pointers). exp[i] is an individual char, for which printf uses %c (it gets promoted to an int when passed to a function, hence the 'int' in the warning).
Also, convention is to return 0 from main for success, and non-zero for errors.