printf char数组段错误C.(printf char array segment fault C)

所以我编写了一个代码,按照正确的顺序对单词进行排序。 这些单词是通过指针存储的,我已经在程序中初始化了另一个char数组来存储char* argv 。

最后一个for循环是打印段故障的原因,我无法弄清楚原因。

#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; }

输入

./a.out orange banana apple

产量

apple banana orange Segmentation fault

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

最满意答案

你的编译器也应该给你一个警告:

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

警告:format指定类型'char *'但参数的类型为'char'[-Wformat]

如果将其更改为%c则可以正常工作

正如警告所说,当你使用它时%s printf期望一个字符串或一个char*并将其视为这样。 a[i]是一个整数类型,可以引用内存中的无效位置。 所以正确的方法是使用%c,然后打印一个字符; 或使用%s并传递char *作为第二个参数。

或者你想要一个args。 改变退场。

char *a[argc-1];

然后更改作业。

a[i-1] = argv[i];

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.

As the warning says, when you use it %s printf is expecting a string or a char* and will treat it as such. a[i] is an integer type that can reference an invalid location in memory. So the correct way to do it would be to either use %c, and print a character; or use %s and pass a char* as the second argument.

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

char *a[argc-1];

Then change the assignment.

a[i-1] = argv[i];

更多推荐