在C中打印数组时出现分段错误

#include #include #include //This program is a sorting application that reads a sequence of numbers from a file and prints them on the screen . The reading from the file here , is a call back function . typedef int (*CompFunc)(const char* , const char* ); typedef int (*ReadCheck)(char nullcheck); char array[100]; //Let this function be done in the library itself. It doesn't care as to where the compare function and how is it implemented. Meaning suppose the function wants to do sort in ascending order or in descending order then the changes have to be done by the client code in the "COMPARE" function who will be implementing the lib code. void ReadFile(FILE *fp,ReadCheck rc) { char a; char d[100]; int count = 0,count1=0; a=fgetc(fp); //printf("%c",a); //count1=(*rc)(a); //printf("%d",count1); while (1 !=(*rc)(a) ) { if(a==' ') { d[count1]='\0'; strcpy(&array[count],d); count=count+1; printf("%s \n",d); memset(d,'\0',100); count1=0; } else { d[count1]=a; count1=count1+1; //a=fgetc(fp); } //printf("%c",a); a=fgetc(fp); } } void Bubblesort(char* array , int size , int elem_size , CompFunc cf) { int i,j,k; int *temp; for( i=0;i < size ;i++) { for ( j=0;j < size -1 ; j++) { // make the callback to the comparision function if(1 == (*cf)(array+j*elem_size,array+ (j+1)*elem_size)) { //interchanging of elements temp = malloc(sizeof(int *) * elem_size); memcpy(temp , array+j*elem_size,elem_size); memcpy(array+j*elem_size,array+(j+1)*elem_size,elem_size); memcpy(array + (j+1)*elem_size , temp , elem_size); free(temp); } } } for (k=0;k<5;k++) printf("%s \n",array[k]); } //Let these functions be done at the client side int Compare(const char* el1 , const char* el2) { int element1 = *(int*)el1; int element2 = *(int*)el2; if(element1  element2) return 1 ; return 0; } int ReadChecked(char nullcheck) { if (nullcheck=='\n') return 1; else return 0; } int main() { FILE *fp1; int k; fp1=fopen("readdata.txt","r"); ReadFile(fp1,&ReadChecked); for (k=0;k<5;k++) printf("%s \n",array[k]); Bubblesort((char*)array,5,sizeof(array[0]),&Compare); printf("after sorting \n"); for (k=0;k<5;k++) printf("%s \n",array[k]); return 0; } 

该数组有数据

  123 11 2312 121 231 

它应该以完全相同的方式打印数据。 尽管它的打印最终会给出分段错误。

array的类型是什么? 如果是int的数组,则应使用%d格式打印,而不是%s

 printf("%d\n", array[k]); 

如果arrayint数组:

如果使用%sprintf函数会将array[k]视为字符串( char* ),因此将取消引用该值打印出那里的字符。 但123(0x7b)是一个无效的地址,因此系统将使用SEGFAULT终止可执行文件。

编译时请启用所有警告。 编译器能够看到类型错误并警告您。


编辑:但array是一个char数组….它只能逻辑地保存1个字符串,而不是5.要打印它你使用

 printf("%s \n", array); // cannot index. 

您最好修改代码的结构。

arrays是什么类型的? 听起来你错误地使用它。

如果你有一个int数组:

 printf("%i \n",array[k]); 

注意%i和%d是输出的同义词。

如果你有一个字符串数组:

%s适用于char*类型的字符串。 这意味着要使用%s你必须确保数组的每个元素都拥有自己的空终止字符串,每个字符串都是char*类型。 确保字符串是具有0终止的字符数组。

您确定它是出现分段故障的printf循环吗? 如果所有数字都按照你说的那样打印出来,则可能是因为它是分段错误的原因。

添加printf(“将它制作到这里。\ n”); 循环后的行确定。

 printf("%s \n",array[k]); 

array [k]是一个字符,而不是字符指针,因此需要使用%c打印,而不是%s。 否则,它将尝试取消引用内存的前256个字节中的地址,从而徒劳地搜索要打印的字符串。