我知道有很多此类主题,但我已经阅读了其中的几个,但仍然无法弄清楚我做错了什么。
我已经成功生成了一个 char** 数组。我的冒泡排序功能可能也适用。但是当我将生成的数组传递给函数时,只复制了 1 行。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
void sort(char** tab)
{
char* temp;
int i, j, size = sizeof(tab)/sizeof(tab[0]);
printf("%d\n", size);
for(i = 0; i < size; ++i)
{
for(j = i+1; j < size; ++j)
{
if(strcmp(tab[j-1], tab[j]) > 0)
strcpy(temp, tab[j-1]),
strcpy(tab[j-1], tab[j]),
strcpy(tab[j], temp);
}
}
for(i = 0; i < sizeof(tab)/sizeof(tab[0]); ++i)
puts(tab[i]);
}
int main()
{
srand(time(NULL));
int size = rand()%5+5, i, j, s;
char** tab = (char**)malloc(size * sizeof(char*));
for(i = 0; i < size; ++i)
{
s = rand()%9+1;
tab[i] = (char*)malloc(s+1);
for(j = 0; j < s; ++j)
tab[i][j] = 'a'+rand()%26;
tab[i][s] = 0;
}
for(i = 0; i < size; ++i)
puts(tab[i]);
puts("");
sort(tab);
return 0;
}
Here代码的工作原理。
当我在函数循环之前写入 size=5 时,它返回段错误。
编辑:与将数组大小作为参数传递相同: http://ideone.com/3Wvncq
最终代码
我已经解决了所有问题,这是 final code . 我将段错误误解为分配固定大小而不是不分配临时变量的结果。 谢谢大家的回答。
最佳答案
不要在函数内部计算大小 void sort(char** tab)
.在这个函数中,它将被计算为 -
int i, j, size = sizeof(tab)/sizeof(tab[0]); // equivalent to sizeof(char **)/sizeof(char*) in function giving wrong length as you desire.
它的长度在 main
中( size
是使用 rand
生成的,所以不需要找到它)然后将它作为参数传递给函数 sort
.
像这样声明你的函数-
void sort(char** tab,size_t size)
并且从主 channel 长度调用时 tab
对它 -
sort(tab,size); // size will be number of elements in tab calculated in main
你会因此得到段错误 -
if(strcmp(tab[j-1], tab[j]) > 0)
strcpy(temp, tab[j-1]),
strcpy(tab[j-1], tab[j]),
strcpy(tab[j], temp);
temp
在 sort
中未初始化你仍然把它传递给strcpy
因此 undefined behavior 。 初始化 temp
在传递给 strcpy
之前.分配内存给temp
在函数中 sort
.
关于c - 将 char** 作为参数传递给 C 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32777476/