gpt4 book ai didi

c - 如何找到指向字符串的指针数组的新大小

转载 作者:行者123 更新时间:2023-12-02 21:58:33 25 4
gpt4 key购买 nike

在 main 方法中,我正在创建一个指向字符串的指针数组 在 add 方法中,我正在重新分配数组大小并添加我不知道的 x 元素 回到 main 时,我如何知道数组的新大小,我的意思是数组中元素的数量?

这是我的代码..(它有一些错误)

#include <stdio.h>

void add(char ***x);

int main()
{
char **s;
s = (char **) malloc(sizeof(char *));
int i;
add(&s);

for( i=1;i<=?????(**find the new size of the array** );i++)
puts(*s[i]);

return 0;
}

void add(char ***x)
{

- ** // alter arry add x random datas to the array of string pointer**

/*
s[1]="Hello";
s[2]="Need";
s[3]="a help";
s[4]="and help";
s[5]="for the help";
*/

char **data;
int i = 0;
for (i = 1; i <= 5; i++)
{
data = (char **) realloc(*x, 1 * sizeof(char *));
data[i] = (char *) malloc(i * sizeof(char *));
strcpy(data[i], "first");
}

}

有人可以指出并修复代码中的错误吗?

最佳答案

(旁注:

can some one please point and fix the bug in the code..

嘿,这不是调试器的用途吗?)

长话短说,手动跟踪它:

char **func_that_reallocs(char **ptr, size_t *sz)
{
char **tmp = realloc(ptr, new_size * sizeof(*ptr));
*sz = new_size;
return tmp;
}

还有 do not cast the return value of malloc()!

关于c - 如何找到指向字符串的指针数组的新大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17336247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com