将 char** 作为参数传递给 C 中的函数

Pass char** as an argument to a function in C

我知道有很多此类主题,但我已经阅读了其中的几个,但仍然无法弄清楚我做错了什么。

我已经成功生成了一个 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 时 returns 分段错误。

编辑: 与将数组大小作为参数传递相同: 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) 

并且从 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);

tempsort 中是 未初始化的 而你仍然将它传递给 strcpy 因此 未定义的行为初始化 temp 传递给strcpy。在函数sort.

中分配内存给temp

在您的 sort 函数中声明 temp 变量:

char* temp;

稍后您将其用作字符串复制的目标(和源):

strcpy(temp, tab[j-1]),

但是你在任何地方都没有让 temp 指向任何地方,temp 未初始化,这会导致 未定义的行为 和你的崩溃。

不要使用指针,而是将其声明为尽可能大的字符串大小的数组。