gpt4 book ai didi

c - 打印出位于动态内存中的数组元素

转载 作者:太空宇宙 更新时间:2023-11-04 00:40:59 25 4
gpt4 key购买 nike

XXX----是的,这是一个家庭作业问题,但是是的,我被困住了。为什么这不打印出数组的元素?请帮助---XXX

好的,我们搞定了打印部分。太感谢了。现在的问题是空格分隔符被放入数组之前的第一个字符。我需要将所有的单词或字符设置到数组中。

int main(int argc, char** argv) {

int size = 0;
char **array = malloc(0); //malloc for dynamic memory since the input size is unknown
static const char filename[] = "input.txt";
FILE *file = fopen(filename, "r");
if (file != NULL) {
char line [ 128 ];

char delims[] = " ";
char *result = NULL;
while (fgets(line, sizeof line, file) != NULL) {
result = strtok(line, delims); //separate by space
size++;
array = realloc(array, size * sizeof (char*)); //declare array with unknown size
array[size - 1] = result;

}
fclose(file);
} else {
perror(filename);
}
return 0;
printf(array); //print array???
return (EXIT_SUCCESS);
}

最佳答案

这是 C。您不能只调用 printf() 并期望它为您完成工作。您需要使用 for() 或 while() 循环遍历数组并打印出每个元素。

假设它是一个字符串数组:

int i;
for (i=0; i<size; i++)
printf("array[%d] = %s\n", i, array[i]);

关于c - 打印出位于动态内存中的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8220919/

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