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

时间:2014-04-25 08:58:26

标签: c pointers struct readfile

好吧,我对malloc和结构似乎有点困难> 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 *输入然后从输入中收集所有数字并将其存储为int在数字.. 我已经有了运行的函数..我可以从文件中读取,我只是在运行结构时遇到问题。

1 个答案:

答案 0 :(得分:2)

此:

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