ฉันต้องการทราบวิธีพิมพ์ค่า char* word
from โครงสร้างนี้
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 และดูเหมือนว่าจะมีสองชื่อภายในลายเซ็นฟังก์ชัน
ถ้าฉันไม่ใช้ฟังก์ชันเพื่อกำหนดค่าให้กับสมาชิก struct ฉันสามารถพิมพ์ค่าของ new_word_count->word ภายใน main.c ได้ไม่มีปัญหา ดังนั้นฉันเชื่อว่าปัญหาของฉันต้องมาจากการเรียกใช้ฟังก์ชัน ขอบคุณล่วงหน้า.
ตัวอย่างขั้นต่ำ ครบถ้วน และตรวจสอบได้:
#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;
}
word_count_struct new_word_count( &word );
ไม่ใช่รหัส C คุณตั้งใจจะเขียนword_count_struct *mystruct = new_word_count( &word );
หรือไม่ โปรดแสดงตัวอย่างที่ทำซ้ำได้น้อยที่สุด คำถามของคุณค่อนข้างไม่ชัดเจน - person Jabberwocky   schedule 11.02.2018