gpt4 book ai didi

C 字符串内存分配,C 字符串表

转载 作者:行者123 更新时间:2023-11-30 19:52:13 25 4
gpt4 key购买 nike

我想制作动态分配的C字符串表,但我想我不太了解这个主题,你能给我解释一下或者更正我的代码吗?

#include <stdio.h>

int main()
{
int i;
char** t;
t=(char**)malloc(16*sizeof(char*));

for(i<0;i<100;i++)
{
*t[i]=(char*)malloc(16*sizeof(char));
}

return 0;
}

最佳答案

您应该使用变量来实现您想要的一切。例如,您为 char* 类型的 16 个元素分配了内存,结果,您有一个包含 16 个元素的数组,但是您会从 0 到 100 吗?为什么?

#include <stdio.h>

int main()
{
int n = 16;
int m = 16;
// Allocate a memory for n elements of type char*
char** t = (char**)malloc(n * sizeof(char*));
for(int i = 0; i < n; ++i)
{
// For each element in array t - initialize with another array.
// Allocate m elements of type char
t[i] = (char*)malloc(m * sizeof(char));

// Initialize
for(int j = 0; j < m; ++j)
t[i][m] = 'a';
}

// Print
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < m; ++j)
printf("%c ", t[i][m]);
printf("\n");
}


// Free allocated memory!
for(int i = 0; i < n; ++i)
free(t[i]);
free(t);
return 0;
}

关于C 字符串内存分配,C 字符串表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23769011/

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