gpt4 book ai didi

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

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

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

//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 中,指针成功地更改了另一个变量的值,而无需使用地址运算符。

//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);
}

最佳答案

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

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

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

如果您希望用户在同一行中同时输入 nameage,并用空格分隔,而 name 则不可以要包含任何空格,您可以这样做

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

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

关于c - 为什么指针需要在其参数中使用地址运算符来修改结构成员的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49316802/

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