C 为什么指针在其参数中需要运算符的地址来修改结构成员的值?
为什么指针“precord”(在代码示例1中)需要运算符的地址来更改结构成员中的值C 为什么指针在其参数中需要运算符的地址来修改结构成员的值?,c,function,pointers,structure,C,Function,Pointers,Structure,为什么指针“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); }
//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);
}
//代码示例1
#包括
结构学生
{int a;};
无效输入(结构学生*);
void main(){
结构学生年龄;
printf(“输入您的年龄”);
输入(年龄);
printf(“%d”,年龄a);
}
无效输入(结构学生*预编码){
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);
}
//代码示例2
#包括
无效输入(int*);
void main(){
智力年龄;
printf(“输入您的年龄”);
输入(年龄);
printf(“%d”,年龄);
}
无效输入(int*precord){
scanf(“%d”,预编码);
}
当我构建您的程序时,我收到以下警告,这些警告涵盖了评论中所说的内容:
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”,并始终检查结果,以便获得预期的匹配值数。您需要将要读入的整数的地址传递到
scanf()
这将允许用户键入name
的值,点击RETURN
,然后键入age
的值,然后点击RETURN
如果希望用户在同一行中键入name
和age
,并用空格分隔,并且name
不包含任何空格,则可以这样做
scanf("%[^ \n] %d", precord->name, &(precord->age));
若要使
scanf()
停止读取name
的字符,当它碰到空格时。在scanf
函数中,我们必须提供变量的地址。但是对于第一个参数,您提供的是数组的基址,而对于第二个参数
,您通过指针取消对结构成员年龄的引用。您必须提供可变年龄的地址。更新您的scanf
参数,如下所示:
我将打印输入。'precord->age'-nope。函数调用无法修改其参数。要从main调用input
,您需要首先声明它。scanf(“%[^\n]%d”,precord->name,&precord->age)
这是另一个让人费解的决定导致混乱的例子,该决定允许数组通过addess传递,而不需要“&”地址运算符。“我认为”调试器没有执行!您是否建议始终使用sscanf而不是scanf%[^\n]?我的意思是“sscanf”比“scanf”能更好地控制输入内容。我现在看到,通过在Stephen Docy的回答中添加一个空格(无论是否使用“scanf”),问题得到了解决;
scanf("%[^ \n] %d", precord->name, &(precord->age));
scanf("%[^\n] %d",precord->name,precord->age);