c 和指针中的 scanf 语句
scanf statement in c and pointers
我读了很多以前的问题,但是 none 消除了我的疑虑。
当我将指针定义并初始化为
int a = 10;
int* p;
p = &a;
printf("%d", *p); // this will print the value of 'a' towards which p is pointing
但是当我使用 scanf 语句时-
int *p;
scanf("%d", &p);
printf("%d", p); // is this form of input similar to the one above?
还有当我使用char指针读取字符串时-
char* name[10];
scanf("%s", name);
printf("%s", name); // runs correctly.
我所知道的是 scanf 期望指针作为输入(如果它像 int a;
就像 &a
)
但是如果我使用--
char* names[5][10];
scanf("%s", names[1]); // reading the first name. Is this correct? because length of name can vary.
现在我无法打印这个,我试了很多方法。
求详细解释,我的老师不是很好
疑问
我们什么时候用指针来使用*
?即打印它的值或为了什么?
无法扫描char* xyz[a][b];
简单解释一下我的错误和上面的代码。
编辑-
int* arr[n];
for(int i =0; i
printf("请输入%d人的工资:", i+1);
scanf("%d", &(arr[i]));
printf("\n");
}
还有,这种赋值方式不对吧?
printf("%d", p); // is this form of input similar to the one above?
不,%d
需要一个 int
参数,您传递的是 int *
。为转换说明符提供不匹配的参数类型会调用未定义的行为。
也就是说,如果
char* name[10]; // array of character pointers!
scanf("%s", name);
printf("%s", name); // runs correctly.
你错了。检查数据类型。 %s
期望参数是指向 char
数组的指针,因此您的代码应该是
char name[10]; // array of characters
scanf("%9s", name); // mandatory error check for success to be done.
printf("%s", name);
因为,在大多数情况下,包括这种情况,数组类型会衰减到指向数组第一个元素的指针,因此当作为函数参数传递时,name
实际上是 [=21 类型=].
同理
char* names[5][10];
scanf("%s", names[1]);
将其更改为
char names[5][10];
就够了。
我读了很多以前的问题,但是 none 消除了我的疑虑。
当我将指针定义并初始化为
int a = 10;
int* p;
p = &a;
printf("%d", *p); // this will print the value of 'a' towards which p is pointing
但是当我使用 scanf 语句时-
int *p;
scanf("%d", &p);
printf("%d", p); // is this form of input similar to the one above?
还有当我使用char指针读取字符串时-
char* name[10];
scanf("%s", name);
printf("%s", name); // runs correctly.
我所知道的是 scanf 期望指针作为输入(如果它像 int a;
就像 &a
)
但是如果我使用--
char* names[5][10];
scanf("%s", names[1]); // reading the first name. Is this correct? because length of name can vary.
现在我无法打印这个,我试了很多方法。
求详细解释,我的老师不是很好
疑问
我们什么时候用指针来使用
*
?即打印它的值或为了什么?无法扫描
char* xyz[a][b];
简单解释一下我的错误和上面的代码。
编辑-int* arr[n];
for(int i =0; iprintf("请输入%d人的工资:", i+1);
scanf("%d", &(arr[i]));
printf("\n");
}
还有,这种赋值方式不对吧?
printf("%d", p); // is this form of input similar to the one above?
不,%d
需要一个 int
参数,您传递的是 int *
。为转换说明符提供不匹配的参数类型会调用未定义的行为。
也就是说,如果
char* name[10]; // array of character pointers!
scanf("%s", name);
printf("%s", name); // runs correctly.
你错了。检查数据类型。 %s
期望参数是指向 char
数组的指针,因此您的代码应该是
char name[10]; // array of characters
scanf("%9s", name); // mandatory error check for success to be done.
printf("%s", name);
因为,在大多数情况下,包括这种情况,数组类型会衰减到指向数组第一个元素的指针,因此当作为函数参数传递时,name
实际上是 [=21 类型=].
同理
char* names[5][10];
scanf("%s", names[1]);
将其更改为
char names[5][10];
就够了。