名称将不会显示

时间:2014-07-12 03:41:09

标签: c pointers struct printf

我的代码编译没有问题,接受输入没有问题,打印没有问题。但是,它不想打印它只打印空间的名称。它正在工作,我做了一些额外的更改,我不知道出了什么问题。任何想法都将不胜感激!

#include <stdio.h>
#include <stdlib.h>

struct File {
char type;
char name;
int time;
int size;
}f;

int main()
{
struct File * c = malloc(1 *sizeof(struct File));
printf("Enter file name: \n");
scanf("%s", &f.name);
printf("Enter the file size: \n", f.size);
scanf(" %d", &f.size);
printf("Enter when the file was last accessed: \n", f.time);
scanf(" %d", &f.time);
printf("Enter the file type: \n", f.type);
scanf("%s", &f.type);
printf("\n");
structPrint();
}

structPrint()
{
printf("Filename: %s, File Size: %d, Type: [%s], Access Time: %d \n", &f.name, f.size,     &f.type, f.time);
}

2 个答案:

答案 0 :(得分:4)

您的结构包含正好1个字符type和1个字符name的空间。这两者都可能比单个字符更长 - 事实上,它们必须,因为它们可能被认为是以空字符结尾的字符串。尝试将它们变成数组......

答案 1 :(得分:1)

您的问题是您将名称和类型存储为chars,而不是char[]。您可以在运行时为它们分配内存,也可以将它们声明为固定大小的数组。我的代码将使用后者。

将结构更改为以下内容:

struct File {
    char type[12]; /*or whatever maximum sizes you think are appropriate */
    char name[64];
    int time;
    int size;
}f;

删除&scanf电话中的printf运营商,了解姓名和类型。