[英]Trying to pass a struct pointer to a function results in error
當我嘗試將 struct 指針傳遞給 function 時出現此錯誤,這是什么意思,為什么我不能傳遞struct*
?
我有多個與此類似的函數都返回相同的錯誤。
我已經嘗試過在 c 中將結構指針傳遞給 function 中提到的解決方案。 但會打印相同的錯誤。 我在下面分別為帶有和不帶有 soln 的兩個程序附加了鏈接
**ERROR**:</p>
$ gcc -o class -Wall -Werror -Wwrite-strings -std=gnu99 -ggdb3 classroster2.c
<p >classroster2.c:15:23:
error: **'struct node' declared inside parameter list will not be visible outside of this definition or declaration [-Werror]**
15 | void enterName(struct node* xptr);
classroster2.c:57:6: **error: conflicting types for 'enterName'**
57 | void enterName(struct node* xptr){
classroster2.c:15:6: **note: previous declaration of 'enterName' was here**
15 | void enterName(struct node* xptr);
struct student{
size_t noClass;
char **classTaken;
};
struct node{
struct student* details;
struct node *next;
char *name;
};
function 在這里
void enterName(struct node* xptr){
printf("\nEnter the name of Student(%d)(max 12)= ",studentNo+1);
xptr->name=malloc(MAX_LENGTH);
alloCheck(xptr->name);
scanCheck(scanf("%s", xptr->name));
studentNames[studentNo] = xptr->name;
studentNo++;
}
調用 function
struct node * studenti =NULL;
init(studenti);
//studentname
enterName(studenti);
PS:完整的代碼可以在這里找到(sry我還在學習git)
將結構聲明放在 function 原型之前
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct student{
size_t noClass;
char **classTaken;
};
struct node{
struct student* details;
struct node *next;
char *name;
};
void tstpt(void);
void prgmSt(void);
void initHead(void);
void scanCheck(int tst);
void alloCheck(void* ptr);
void inputCheck(int x);
void init(struct node* wptr);
void enterClassNo(struct node* yptr);
void enterName(struct node* xptr);
void enterClassTaken(struct node* zptr);
您需要在任何 function 原型之前前向聲明結構node
,或者在使用指向該結構的指針的任何 function 原型之前完全聲明結構,因為編譯器從上到下讀取文件。
否則編譯器在引用指向該結構的指針作為參數類型時不知道node
是什么,因為它沒有引用。 它是“困惑的”並拋出一個診斷,表明您將嘗試在參數列表中完全聲明此結構。
結構node
的前向聲明:
struct node;
void init(struct node* wptr);
void enterClassNo(struct node* yptr);
void enterName(struct node* xptr);
void enterClassTaken(struct node* zptr);
struct node {
struct student* details;
struct node *next;
char *name;
};
或者
function原型之前的結構node
聲明:
struct node {
struct student* details;
struct node *next;
char *name;
};
void init(struct node* wptr);
void enterClassNo(struct node* yptr);
void enterName(struct node* xptr);
void enterClassTaken(struct node* zptr);
不保證您的程序沒有其他問題。 另外我不明白為什么你需要指向指針版本的指針。 這似乎很容易出現問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.