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];
j--;
}
argv[j+1] = key;
}
for(i = 1; i < argc; i++){
a[i-1] = *argv[i];
}
for (i = 1; i < argc ; i++){
puts(argv[i]);
}
for(i = 0; i < argc-1; i++){
printf("%s", a[i]);
}
return 0;
}
input
./a.out orange banana apple
output
apple
banana
orange
Segmentation fault
tolower(argv[i])should be rasing a warning from the compiler, otherwise it's because you did not enable them, do not ignore them at all! Warnings are very useful for expert programmers, thy must be a tool for non experts.