【发布时间】:2020-04-27 00:55:44
【问题描述】:
我一直在尝试对字符串数组进行冒泡排序,但我总是收到“分段错误”错误。 任何帮助表示赞赏。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *arreglo[20]={"Ruben","Modesta","Jan","Ana","Amparo","Josu","Azahara","Concepcio","Carmelo","Miguel","Francesc","Jairo","Jose","Luis","Teo","Jone","Jacobo","Ainoa","Natalia","Igor"};
int i;
int j;
char *temp;
for (int j=0; j<20; j++)
{
for (int i=j+1; i<20; i++)
{
if (strcmp(arreglo[j], arreglo[i]) > 0)
{
strcpy(temp, arreglo[j]);
strcpy(arreglo[j], arreglo[i]);
strcpy(arreglo[i], temp);
}
}
}
}
【问题讨论】:
-
您的字符串是 String Literals 并且在只读内存中。
temp也是一个未初始化的指针,它不指向任何地方。写入任何一个都可以保证 SegFault。你翻了个“蛇眼”。 -
我明白了,谢谢!
-
您可能想试试
valgrind工具。使用-g编译您的程序,然后使用valgrind ./your_program运行它。它将向您显示有关分段错误的详细信息。你会看到它发生在哪一行。
标签: c bubble-sort