sleep-elite sleep-elite - 1 year ago 206
C Question

printf char array segment fault C

So I have written a code that sorts words in the right order. The words are being stored via pointers and I have initialized another char array in the program to store the

char* argv

The last for loop is what prints segment fault and I can't figure out why.

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) {
int i, j;
char *key;
char a[argc-1];
for(i=1; i < argc; i++){
a[i-1]= tolower(argv[i]);

for (i = 2; i < argc; i++) {
key = argv[i];

j = i-1;
while (j >= 1 && strcmp(argv[j], key) > 0) {
argv[j+1] = argv[j];

argv[j+1] = key;

for(i = 1; i < argc; i++){
a[i-1] = *argv[i];

for (i = 1; i < argc ; i++){

for(i = 0; i < argc-1; i++){
printf("%s", a[i]);
return 0;


./a.out orange banana apple


Segmentation fault

Answer Source

Your compiler should also give you a warnging on:

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

warning: format specifies type 'char *' but the argument has type 'char' [-Wformat]

If you change that to a %cit works fine.

Or perchance you want args in a. Change the delcaration.

char *a[argc-1];

Then change the assignment.

a[i-1] = argv[i];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download