Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C:realloc是一个字符串数组_C_Arrays_String_Realloc - Fatal编程技术网

C:realloc是一个字符串数组

C:realloc是一个字符串数组,c,arrays,string,realloc,C,Arrays,String,Realloc,我想用函数重新分配字符串数组。我写了一个非常简单的程序来演示。我希望输出字母“b”,但得到NULL void gain_memory(char ***ptr) { *ptr = (char **) realloc(*ptr, sizeof(char*) * 2); *ptr[1] = "b\0"; } int main() { char **ptr = malloc(sizeof(char*)); gain_memory(&ptr); print

我想用函数重新分配字符串数组。我写了一个非常简单的程序来演示。我希望输出字母“b”,但得到NULL

void gain_memory(char ***ptr) {
    *ptr = (char **) realloc(*ptr, sizeof(char*) * 2);
    *ptr[1] = "b\0";
}

int main()
{
    char **ptr = malloc(sizeof(char*));
    gain_memory(&ptr);
    printf("%s", ptr[1]); // get NULL instead of "b"
    return 0;
}

多谢各位

应在增益内存中的*ptr周围加括号:

(*ptr)[1] = "b\0";

如果没有为字符串数组中的实际字符串分配任何内存,则需要执行以下操作:

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

void gain_memory(char ***ptr, int elem) {
    *ptr = (char**)realloc(*ptr, 2*elem*sizeof(char*));
    (*ptr)[1] = "b";
}

int main()
{
    //How many strings in your array?
    //Lets say we want 10 strings
    int elem = 10;
    char **ptr = malloc(sizeof(char*) * elem);
    //Now we allocate memory for each string
    for(int i = 0; i < elem; i++)
        //Lets say we allocate 255 characters for each string
        //plus one for the final '\0'
        ptr[i] = malloc(sizeof(char) * 256);

    //Now we grow the array
    gain_memory(&ptr, elem);
    printf("%s", ptr[1]);
    return 0;
}
#包括
#包括
#包括
无效增益存储器(字符***ptr,整数){
*ptr=(char**)realloc(*ptr,2*elem*sizeof(char*);
(*ptr)[1]=“b”;
}
int main()
{
//数组中有多少个字符串?
//假设我们想要10个字符串
整数=10;
char**ptr=malloc(sizeof(char*)*elem);
//现在我们为每个字符串分配内存
for(int i=0;i
[]运算符的优先级高于*,因此这样更改代码将正常工作

(*ptr)[1] = "b";

请注意,“\0”是不必要的。

不要使用
realloc
的返回,这毕竟是C。(这样做可能会隐藏编译器可能会告诉您的问题。)此外,不要立即将
realloc
的结果分配给要重新分配的指针。如果
realloc
失败,则表示您丢失了原始指针并泄漏了内存。(哦,还要检查分配失败。)他不需要为示例中的实际字符串分配内存,因为他只为其中一个指针分配一个常量字符串。