为什么我的程序不打印出最终结果?

发布于 2025-01-28 07:26:51 字数 789 浏览 2 评论 0原文

为什么当我运行此代码以输入用户的字符串输入时,为什么它不打印出最终结果?

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酒废 2025-02-04 07:26:51

text已经是char *,因此您不必将&amp; text 转换为scanf,而是仅文本

scanf将指针作为参数以修改指向值,但是如果将char ** **作为参数,您将修改到字符串的指针而不是尖的字符串

text is already a char *, so you don't have to pass &text to scanf, but only text.

scanf takes a pointer as argument in order to modify the pointed value, but if you pass a char ** as an argument, you will modify the pointer to the string instead of the pointed string

北笙凉宸 2025-02-04 07:26:51

您只需要从&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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文