gpt4 book ai didi

c - 如何调用已使用结构指针函数填充的结构成员

转载 作者:行者123 更新时间:2023-11-30 16:35:50 24 4
gpt4 key购买 nike

我想知道如何从此结构中打印char* word的值。

  struct word_count_struct {
char *word;
int count;
};

该结构已被赋予思考功能的值

struct word_count_struct *new_word_count( char *word )
{
struct word_count_struct *new_word_count = (struct word_count_struct *)malloc(sizeof(struct word_count_struct));

new_word_count->word = "Hello";
new_word_count->count = 1;

return new_word_count;
}

当我使用 word_count_struct new_word_count( &word );new_word_count( &word ); 调用函数和 puts(new_word_count->word);时code> 打印 main.c 中的成员,

我收到错误消息

error: called object ‘new_word_count’ is not a function or function pointer

note: declared here
struct word_count_struct *new_word_count;

我特别不确定的是函数调用,我知道对于任何其他函数,我通常会使用代码 function_name(passing argument); 但这个函数返回一个结构指针,并且似乎是函数签名中的两个名称。

如果我不使用函数为结构成员赋值,我可以在 main.c 中打印出 new_word_count->word 的值,没有问题,所以我相信我的问题一定来自函数调用。预先感谢您。

最小、完整且可验证的示例:

#include <stdio.h>
#include <stdlib.h>

struct word_count_struct {
char *word;
int count;
};

struct word_count_struct *new_word_count( char *word );

int main()
{
struct word_count_struct *wordcountptr;
char *word = "Hello";

wordcountptr = new_word_count(word);
puts(wordcountptr->word); /* print out the string "Hello" which was assigned to this struct member though the word_count_struct function */
free(wordcountptr);
return 0;
}

/* this function should take the value of the passing argument and assign it to the word member of struct word_count_struct and then return a pointer to that struct */
struct word_count_struct *new_word_count( char *word )
{
struct word_count_struct *new_word_count;
new_word_count = (struct word_count_struct *)malloc(sizeof(struct word_count_struct)); /* allocate memory for struct */

new_word_count->word = &word; /* assign the memory address of passing argument to this member */
new_word_count->count = 1;

return new_word_count;

}

最佳答案

您可能想要这个:

struct word_count_struct *wordcountptr;
char *word;
wordcountptr = new_word_count(word);
puts(wordcountptr->word);

此代码可以编译并运行,但它或多或少没有用,因为 new_word_count 函数尚未完成。

问题已更改...

问题现在在这里:

你需要这个:

new_word_count->word = word;

而不是

new_word_count->word = &word;

顺便说一句,你的编译器应该警告你。

完整功能:

struct word_count_struct *new_word_count(char *word)
{
struct word_count_struct *new_word_count;
new_word_count = (struct word_count_struct *)malloc(sizeof(struct word_count_struct));

new_word_count->word = word;
new_word_count->count = 1;

return new_word_count;
}

但是使用这种方法,您很可能会遇到其他问题,因为您只存储要计数的单词的地址,但您可能更想存储单词本身。而不是:

new_word_count->word = word;

您可能需要:

new_word_count->word = malloc(strlen(word) + 1);  // allocate memory for word
strcpy(new_word_count->word, word); // copy the word

关于c - 如何调用已使用结构指针函数填充的结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48732509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com