为什么指针需要在其参数中使用address-of运算符来修改结构成员的值?

时间:2018-03-16 09:08:04

标签: c function pointers structure

为什么指针“precord”(在代码示例1中)需要一个address-of运算符来更改结构成员中的值?

//Code Sample 1

#include <stdio.h>

struct student
{int a;};

void input(struct student *);

void main() {
  struct student age;
  printf("Enter Your Age\n");
  input(&age);
  printf("%d",age.a);
}

void input(struct student *precord) {
  scanf("%d",&precord->a);
}

指针成功设法在代码示例2中更改了没有address-of运算符的另一个变量的值。

//Code Sample 2
#include <stdio.h>

void input(int *);
void main() {
  int age;
  printf("Enter Your Age\n");
  input(&age);
  printf("%d",age);
}

void input(int *precord) {
  scanf("%d",precord);
}

3 个答案:

答案 0 :(得分:2)

您需要将要读取的整数的地址传递给scanf()

scanf("%[^\n] %d", precord->name, &(precord->age));

这将允许用户输入name的值,点击RETURN,然后输入age的值并点击RETURN

如果您希望用户在同一行上同时输入nameage,并用空格分隔,并且name不包含任何空格,则可以< / p>

scanf("%[^ \n] %d", precord->name, &(precord->age));

scanf()在遇到空格时停止阅读name的字符。

答案 1 :(得分:1)

当我构建你的程序时,我收到以下警告,其中包含评论中所说的内容:

sc.c: In function ‘main’:
sc.c:15:3: warning: implicit declaration of function ‘input’ [-Wimplicit-function-declaration]
   input(&record);
   ^
sc.c: At top level:
sc.c:19:6: warning: conflicting types for ‘input’
 void input(struct student *precord)
      ^
sc.c:15:3: note: previous implicit declaration of ‘input’ was here
   input(&record);
   ^
sc.c: In function ‘input’:
sc.c:22:10: warning: format ‘%d’ expects argument of type ‘int *’, but argument 3 has type ‘int’ [-Wformat=]
    scanf("%[^\n] %d",precord->name,precord->age);
          ^

还有一个问题,即%[^ \ n]占用了整条线,因此输入例如“Mike 25”会使“Mike 25”成为名称,然后等待年龄下一行。

我建议不要使用'scanf'。将行读入字符串,然后使用'sscanf',并始终检查结果,以便获得您期望的匹配值的数量。

答案 2 :(得分:1)

scanf函数中,我们必须提供variable的地址。但是对于第一个参数的情况,您提供的是base address of the array but for the second argument,您通过指针取消引用结构成员的年龄。你必须提供变量年龄的地址。更新您的scanf参数,如下所示:

scanf("%[^\n] %d",precord->name,precord->age);

我会打印输入。