-4

这 ; 在编译器期望 void 之前。我真正的问题是:我能够输入 ID 和名称,但在 printf 中看不到它。是不是因为我的数据没有记录在指针里?如何解决问题?

#include <stdio.h>
struct data 
{
 int* ID;
 char* Name;
};

int main(void)
{
    struct data data1;
    struct data *data1Ptr;
    data1Ptr = &data1;
    printf("New ID:\n");
    scanf("%d",data1.ID);
    printf("Name:\n");
    scanf("%s",data1.Name);
    printf("The new ID is \n",&data1.ID);
    printf("The name input is \n",&data1.Name);

    return 0;
}
4

3 回答 3

2

你没有printf()正确使用。

它不会神奇地处理任何参数的格式化:您必须使用格式说明符(以 开头)告诉它%您要发送的参数以及您希望它们的值去哪里。

你需要:

printf("The new ID is %d\n", data1.ID);
printf("The name input is '%s'\n", data1.Name);

另请注意,ID不应该int *,它需要存储一个实际的整数,所以它应该int只是。

于 2013-04-04T15:19:34.410 回答
2
#include <stdio.h>
#include <stdlib.h> /* for malloc and free */

struct data 
{
    /*int* ID; why a pointer? */
    int ID;
    char *Name;
};

/* void main() Noooo */
int main(void)
{
    struct data data1;
    struct data *data1Ptr; /* unused */

    data1Ptr = &data1;
    printf("New ID:\n");
    scanf("%d", &data1.ID); /* scanf expects a pointer */
    printf("Name:\n");
    /* you have to reserve mem for name before */
    data1.Name = malloc(100);
    /* check result of malloc here */
    scanf("%s",data1.Name);
    /*printf("The new ID is \n",data1.ID); You forget %d */
    printf("The new ID is %d\n",data1.ID);
    /* printf("The name input is \n",data1.Name); You forget %s */
    printf("The name input is %s\n",data1.Name);
    free(data1.Name);
    return 0;
}

注意:如果您将 Name 声明为char Name[100]inside struct data,则无需malloc

于 2013-04-04T15:28:28.923 回答
1

你这里似乎有很多问题。首先,您选择在结构中创建NameID指针。这意味着您需要在开始使用它们之前为两者动态分配内存:

struct data data1;
data1.ID = malloc(sizeof(int));
data1.Name = malloc(50); // so arbitrary amount big enough for a name.

我不确定你为什么选择创建ID一个指针,它不一定在这个例子中,如果不是,它可能更容易理解;所以考虑改变它。

现在scanf()需要一个格式字符串和许多指向正在读取的每种类型的指针。在您的情况下,您只是在读取一个 int 和一个字符串,所以您拥有的是:

scanf("%d",data1.ID);
scanf("%s",data1.Name);

很好,请记住,如果您选择更改ID为 aint而不是指针,则需要传递它的地址:scanf("%s",&data1.ID);

printf()接受一个格式字符串,以及要打印的格式的数据。在你的情况下:

printf("The new ID is \n",&data1.ID);  // you're giving the address of the int
printf("The name input is \n",&data1.Name); // and the address of the string

但是您没有提供任何格式...并且您不想发送指针的地址,这没有意义。

printf("The new ID is %d\n",*data1.ID);  // %d for an int, and * to dereference
printf("The name input is %s\n",data1.Name); // %s for a string

您想要做的是相应地使用int%d%s字符串(就像 with 一样scanf()),但是由于ID是指针,因此您需要在将其传递给printf(). C 中没有“字符串”类型,所以当你告诉printf()期待一个字符串时,它只需要一个char *已经data1.Name存在的字符串。

于 2013-04-04T15:42:20.493 回答