Matthew
Matthew

Reputation: 358

C application error on run

I've built a C application, and when I build it, it shows no errors, but when I run it, it gives me the error "Segmentation Fault: 11". If it helps, here is the code I am using:

#include <stdio.h>
int main(char *argv[]) {
printf("The project path is: ./Projects/%c", argv[1]);
return 0;
}

Upvotes: 0

Views: 84

Answers (5)

Jerry Coffin
Jerry Coffin

Reputation: 490048

First, change your main to:

int main(int argc, char *argv[]) 

Second, you have a mismatch between what you're passing to printf, and what you've told it you're going to pass. argv[1] is a pointer to characters, not a character. You need/want to use the %s conversion to print it out:

printf("The project path is: ./Projects/%s", argv[1]);

In this specific case, it's not really mandatory to check for enough arguments, because even if you don't pass any command line arguments, argv will contain at least argv[0] followed by a null pointer. As such, using argv[1] is safe, but if you haven't passed a command line argument, may print as something like (null).

Nonetheless, you generally want to check the value of argc before using argv. In this case, you can get away with it, but only more or less by accident. Trying to use argv[2] the same way could give undefined behavior.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881113

You have a number of problems:

  • The signature for main is an argument count followed by an array of C strings.
  • You should always check the count before using the array.
  • The array is of strings so you need %s to print them.

This should work:

#include <stdio.h>
int main(int argc, char *argv[]) {
    if (argc < 2)
        fprintf (stderr, "Wrong number of arguments\n");
    else
        printf ("The project path is: ./Projects/%s\n", argv[1]);
    return 0;
}

Upvotes: 1

vhallac
vhallac

Reputation: 13907

In addition to the other suggestions, you may need to revisit your printf format. %c is used to print a single character, and argv[1] is char *. Either use argv[1][0] or some such, or use the string format specifier, %s.

Upvotes: 0

Andreas Brinck
Andreas Brinck

Reputation: 52519

  1. Change the signature to int main(int, char*[]);
  2. What arguments are you passing to the process? If you're not passing any argv[1] is out of range

Upvotes: 0

ouah
ouah

Reputation: 145829

The correct main prototyped syntax is

int main(int argc, char *argv[]) { ... }

Also %c conversion specification in printf prints a character, to print a string use %s.

Upvotes: 3

Related Questions