【问题标题】:How to print this string in C when I have the pointer to it?当我有指向它的指针时,如何在 C 中打印这个字符串?
【发布时间】:2022-01-20 09:57:10
【问题描述】:

我是一名 Java 开发人员,我正在学习 C,我想打印一个 string,但它不起作用。我发现与 Java 相比,在 C 中打印 string 非常困难。

这是代码:

static struct t_node* create_tnode(char* n) {
        // Assigning memory to struct variable temp
        struct t_node *temp=(struct t_node * )malloc(sizeof(struct t_node ));
        printf("name = %s\n", temp->name);
        // Assigning value to name variable of temp using arrow operator
        temp->name=n;
        temp->next_dfile=NULL;
        temp->next_file=NULL;

        return temp;
}

打印此temp->name 不起作用,然后我尝试以这种方式打印*temp->name 或类似此&temp->name 并且不起作用。还有一个问题,这个结构是返回 temp var 还是指向 temp 的指针?提前谢谢!

【问题讨论】:

  • 这个 printf 调用的输出是什么?
  • temp 里面没有任何内容,您只是分配了它 - 您是否尝试在分配 temp->name=n; 之后执行 printf
  • 在将 n 分配给 temp->name 之后放置打印功能。它不会返回 temp 本身。它返回值(地址)临时指针所持有的内容。

标签: c string pointers char


【解决方案1】:

你应该在给它赋值后打印变量。这将起作用,

    static struct t_node* create_tnode(char* n) {
        // Assigning memory to struct variable temp
        struct t_node *temp=(struct t_node * )malloc(sizeof(struct t_node ));
                // Assigning value to name variable of temp using arrow operator
        temp->name=n;
        printf("name = %s\n", temp->name);

        temp->next_dfile=NULL;
        temp->next_file=NULL;

        return temp;
}

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 2015-12-26
    相关资源
    最近更新 更多