Saya ingin tahu cara mencetak nilai char* word
dari struktur ini.
struct word_count_struct {
char *word;
int count;
};
Struktur ini telah diberi nilai pikir fungsinya
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;
}
Saat saya menggunakan word_count_struct new_word_count( &word );
atau new_word_count( &word );
untuk memanggil fungsi dan puts(new_word_count->word);
untuk mencetak anggota dari main.c,
Saya mendapatkan pesan kesalahan
error: called object ‘new_word_count’ is not a function or function pointer
Dan
note: declared here
struct word_count_struct *new_word_count;
Yang secara khusus saya tidak yakin adalah pemanggilan fungsi, saya tahu dengan fungsi lain saya biasanya menggunakan kode function_name(passing arguments);
tetapi fungsi ini mengembalikan pointer struct dan sepertinya ada dua nama di dalam tanda tangan fungsi.
Jika saya tidak menggunakan fungsi untuk memberikan nilai ke anggota struct, saya dapat mencetak nilai new_word_count->word dalam main.c tidak ada masalah, jadi saya yakin masalah saya pasti berasal dari pemanggilan fungsi. Terima kasih sebelumnya.
Contoh Minimal, Lengkap dan dapat diverifikasi:
#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 );
bukan kode C. Apakah Anda bermaksud menulisword_count_struct *mystruct = new_word_count( &word );
. Harap tunjukkan contoh minimal yang dapat direproduksi, pertanyaan Anda agak tidak jelas. - person Jabberwocky   schedule 11.02.2018