为什么我的程序不打印出最终结果?
为什么当我运行此代码以输入用户的字符串输入时,为什么它不打印出最终结果?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Function Declerations */
/* Global Variables */
char *text = NULL;
int size;
int main(){
/* Initializing Global Variables */
printf("enter a number limit for text: ");
scanf("%d", &size);
/* Initial memory allocation */
text = (char *) malloc(size * sizeof(char));
if(text != NULL){
printf("Enter some text: \n");
scanf("%s", &text);
// scanf(" ");
// gets(text);
printf("You inputed: %s", text);
}
free(text);
return 0;
}
/* Function Details */
实际上,最终结果看起来像这样
enter a number limit for text: 20
Enter some text:
jason
why when i run this code to take in a string input by the user why does it not print out the final result ?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Function Declerations */
/* Global Variables */
char *text = NULL;
int size;
int main(){
/* Initializing Global Variables */
printf("enter a number limit for text: ");
scanf("%d", &size);
/* Initial memory allocation */
text = (char *) malloc(size * sizeof(char));
if(text != NULL){
printf("Enter some text: \n");
scanf("%s", &text);
// scanf(" ");
// gets(text);
printf("You inputed: %s", text);
}
free(text);
return 0;
}
/* Function Details */
in fact the end result looks like this
enter a number limit for text: 20
Enter some text:
jason
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
text
已经是char *
,因此您不必将&amp; text
转换为scanf
,而是仅文本
。scanf
将指针作为参数以修改指向值,但是如果将char ** **
作为参数,您将修改到字符串的指针而不是尖的字符串text
is already achar *
, so you don't have to pass&text
toscanf
, but onlytext
.scanf
takes a pointer as argument in order to modify the pointed value, but if you pass achar **
as an argument, you will modify the pointer to the string instead of the pointed string您只需要从&amp; text 中删除地址,因为文本是指针,字符串总是指向第一个字符。
you just have to remove the address from &text because text is a pointer and the string always pointe to the first character.