繁体   English   中英

通过C中的函数更改动态2D char数组?

[英]Change a dynamic 2D char array through a function in C?

我正在创建此示例运行,以便可以更好地理解如何通过其他函数编辑动态数组,但是一旦添加了辅助函数,我便开始遇到段错误。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void other_side(char ***funk);

int main()
{
    int i;
    char *argv[11] = {"fish", "dish", "lags", "fags", "shag", "cool", "bean", "rekt", "noon", "coon", "lolz"};

    char **yep, **nop;
    yep = malloc(10 * sizeof *yep);
    if(!yep) { // <-----------------added check for malloc error
        printf("Error: failure to allocate memory\n");
        exit(1);
    }

    printf("10 times %lu\n\n", sizeof *yep);
    for(i = 0; i<10; i++) {
        yep[i] = strdup(argv[i]);
        printf("%s is in yep.\n", *(yep+i)); 
    }
    nop = realloc(yep, 11 * sizeof *yep); //you reallocate to the new total size.
    if(nop == NULL) {
        printf("Error: failure to allocate memory\n")
        exit(1);
    }
    yep = nop;
    *(yep+10) = strdup(argv[10]); 
    printf("Last but certainly not least, %s is in yep.\n", *(yep+10));

    printf("Now to send yep over to the other side and have its values changed.\n");

    other_side(&yep);

    printf("Did it change?\n\n");

    for(i=0; i<11; i++)
        printf("%s is in yep.\n", *(yep+i));

    for(i=0; i<11; i++) { //issue fixed when added strdup() above, previously static
        free(*(yep+i)); 
    }
    free(yep);
    return 0;
}

void other_side(char ***funk)
{
    char *arr[11] = {"dude","yeah","gnar","nice","epic","need","more", "word","four","this","test"};
    int i;
    for(i=0; i<11; i++) {
        **(funk+i) = strdup(arr[i]); //added strdup() here as well
        printf("%s is currently in yep.\n", **(funk+i));
    }
    printf("\n");
}

我注意到的几件事是,当我尝试将main的第11个内存块释放到数组中时,Valgrind注意到了不必要的释放。 我不确定这是否是我的问题,但我也注意到该函数只会在导致分段错误之前更改两个单词。

编辑说明:自编辑以来,我仍然遇到段错误,但是valgrind对正在发生的事情更加清楚。 (对位于地址0x400B18的映射区域的错误权限)

您关于运算符的优先顺序很重要,并且您错过了两个括号以确保操作正确。 这: **(funk+i)意思是: *(funk[i]) ,而不是您想要的(*funk)[i]

这个:

**(funk+i) = strdup(arr[i]);
printf("%s is currently in yep.\n", **(funk+i));

应该是这样的:

*((*funk)+i) = strdup(arr[i]);
printf("%s is currently in yep.\n", *((*funk)+i));

坦率地说,它很容易理解为:

(*funk)[i] = strdup(arr[i]);
printf("%s is currently in yep.\n", (*funk)[i]);

我将其余的内存管理留给您解决。 (即,您在上述循环代码中覆盖的所有指针所指向的动态内存泄漏)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM