Thread: strings

  1. #1
    Registered User
    Join Date
    Mar 2008


    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!

    #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; 
                    printf("Try again using format ./a.out \"<expression>\"\n");
                    return 0;
            strcpy(exp, argv[1])
            return 1;

  2. #2
    Registered User
    Join Date
    Nov 2010
    Long Beach, CA
    Compile with your warnings turned all the way up:
    $ 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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Swapping strings in an array of strings
    By dannyzimbabwe in forum C Programming
    Replies: 3
    Last Post: 03-03-2009, 12:28 PM
  2. malloc() strings VS array strings
    By Kleid-0 in forum C Programming
    Replies: 5
    Last Post: 01-10-2005, 10:26 PM
  3. Table mapping Strings to Strings
    By johnmcg in forum C Programming
    Replies: 4
    Last Post: 09-05-2003, 11:04 AM
  4. converting c style strings to c++ strings
    By fbplayr78 in forum C++ Programming
    Replies: 6
    Last Post: 04-14-2003, 03:13 AM
  5. finding strings in strings
    By watshamacalit in forum C Programming
    Replies: 14
    Last Post: 01-11-2003, 01:08 AM