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

时间:2018-02-11 14:25:04

标签: c pointers struct

我想知道如何从此结构中打印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);从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 arguments);但是这个函数返回一个结构指针,函数签名中似乎有两个名字

如果我不使用函数为struct成员赋值,我可以在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;

}

1 个答案:

答案 0 :(得分:0)

你可能想要这个:

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;

BTW你的编译器应该警告过你。

完成功能:

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