【发布时间】:2019-02-26 04:37:58
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sortString(char *s[], int count);
int main(){
int i;
char buff[BUFSIZ];
int count;
// 's' is a pointer to a char pointer, initially 's' is allocated storage for one char pointer
char** s= malloc(sizeof(char*));
printf("Here is the list of unsorted names: \n\n");
// Keep on reading unlimited number of names until EOF (Ctrl + D) is reached
for (count = 0; fgets(buff, sizeof(buff), stdin); count++){
//Step 1: allocate sufficient storage for s[n] to store the content in buff plus one byte for '\0'
s[count]=malloc(strlen(buff)+1);
//Step 2: copy the contents of 'buf' to 's[n]'
strcpy(s[count],buff);
//Step 3: resize the array of pointers pointed to by 's' to increase its size for the next pointer
*s=realloc(*s,sizeof(char **)*count+2);
printf("added to the array at s[%i] is : %s",count, s[count]);
}
// EOF reached. Now count the number of strings read
printf("\nCount is %d\n\n", count);
// Now sort string using sortString function
// Step 4: implement sortString function for the above-mentioned function declaration
//sortString(s, count);
// Step 5: print the list of sorted names.
int k;
for(k=0; k<count; k++){
printf("%s", s[k]);
}
// Step 6:free the allocated memory.
return 0;
}
void sortString(char *s[], int count){
char * temp;
int j,k;
for(j = 0; j < count -1; j++){
for(k=j+1; k < count; k++){
if(strncmp(s[k],s[k+1],1)>0){
temp=s[k];
s[k]=s[k+1];
s[k+1] = temp;
}
}
}
}
充分披露,这是一项功课。
这个想法是这样的: 我们有一个指针 s,它指向更多的 char 指针,它们本身就是 char 数组指针。然后我们 malloc 这些指针以适应用户输入的字符串,然后重新分配以适应更多的字符串。
malloc 和 realloc 看起来不错。我添加了一行来检查我在每个数组索引处添加的内容,它似乎工作得很好。
当我尝试打印时出现问题。我在第 5 步遇到了段错误,特别是 printf 语句。看起来 s[k] 似乎适用于 4 之前的任何正整数,因为当 k 大于 4 时它会出现段错误。
使用 gcc -g、ubuntu 18.04 和 windows 10 编译。都面临同样的问题。
【问题讨论】:
-
建议
sizeof(char **)*count+2-->sizeof(char *)*(count+2) -
@chux 指出了罪魁祸首。他真快:) 这里是你的代码的现场测试:segfault.stensal.com/a/w7F5k2UFdGb2o9PL,你可以对段错误进行自我诊断。