【发布时间】:2015-09-15 20:17:47
【问题描述】:
所以我基本上是在尝试输入 scanf 的字母(它们之间没有间距),将每个字母放入一个数组中,并使用动态分配的数组 (malloc) 将相应的字母吐出到数组中。
崩溃
#include <stdio.h>
#include <stdlib.h>
int main () {
char *userInput = malloc(sizeof(char)*3); /* dynamic */
scanf("%s", &userInput);
printf("user inputed %c", userInput[1]);
free(userInput);
return 0;
}
运行
#include <stdio.h>
#include <stdlib.h>
int main () {
char userInput [3]; /* array */
scanf("%s", &userInput);
printf("user inputed %c", userInput[1]);
return 0;
}
输入: asd
输出: s
我对动态分配数组的理解是 char userInput [3]; 等同于 char *userInput = malloc(sizeof(char)*3); 但显然从这种情况来看这不是真的?有人愿意解释/帮助吗?
【问题讨论】:
-
问题不在于数组声明。相反,问题在于对 scanf() 及其格式字符串的调用。强烈建议阅读 scanf() 的手册页。事实上,两个发布的代码集都表现出相同的未定义行为