gpt4 book ai didi

C、结构 malloc 和指针。我迷路了

转载 作者:行者123 更新时间:2023-11-30 20:14:56 25 4
gpt4 key购买 nike

好吧,我似乎对 malloc 和 structs 有点困惑 >P

#include ****
#include "func.h"

int main()
{
struct fileData *fileData = (struct fileData*)malloc(sizeof(struct fileData));
fileData->filePath = "text";
printf(%c\n, *fileData->filePath);
}

在 func.h 文件中:

#ifndef func
#define func

typedef struct fileData
{
char *filePath;
char *input;
int *numbers;
}

它只打印第一个“T”,然后程序停止,我不知道它应该如何,我已经尝试了一段时间了哈哈

我想要做的是有一个结构,其中包含程序运行后选择的文件路径,然后读取该文本文件并用整个输入填充 char *input,然后收集输入中的所有数字并将其存储为 int在数字..我已经运行了这些函数..我可以从文件中读取,我只是在运行结构时遇到问题。

最佳答案

这个:

printf(%c\n, *fileData->filePath);

无法编译,第一个参数周围没有任何引号。

解决这个问题,我们得到:

printf("%c\n", *fileData->filePath);

它将精确打印一个字符,该字符是通过跟踪 fileData->filePath 指针找到的。

如果你想打印全名,你应该使用%s:

printf("%s\n", fileData->filePath);

请注意星号是如何删除的,因为现在我们将字符串第一个字符的地址传递给 printf()

此外,please don't cast the return value of malloc() in C .

关于C、结构 malloc 和指针。我迷路了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23288582/

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