2014-03-26 93 views
0

我想在函數中傳遞結構成員。我的意思不是這樣的事情:在函數中傳遞結構成員

struct smth 
{ 
    int n; 
}; 

void funct(struct smth s); 

我想這些結構

struct student { 
char name[50]; 
int semester; 
}; 

struct prof { 
char name[50]; 
char course[50]; 
}; 

struct student_or_prof { 
    int flag; 
    int size; 
    int head; 
    union { 
    struct student student; 
    struct prof prof; 
    } 
}exp1; 
struct student_or_prof *stack; 
struct student_or_prof exp2; 

其成員通過與變量溫控功能而不是struct變量

int pop(int head,int n) 
{ 
if(head==n) 
    return 1; 
else head++; 
} 

因爲我不t只想使用該功能的結構。可能嗎?

編輯我希望數字也改變,而不是像指針一樣返回。

EDIT_2另外我知道這個彈出(exp1.head,n)它的工作原理,但我也希望exp1.head在函數彈出結束後更改。

+0

你可以傳遞結構變量的地址並使用它。你需要一些其他的方式比指針? – LearningC

+0

我想盡一切辦法,但我想要的結構,我發送功能的成員的數量也改變這就是爲什麼我提到指針 – valkon

回答

2

使用指針。通過poniter到exp1.head並通過功能提領它操縱它,

int pop(int * head,int n) 
{ 
if(*head==n) 
    return 1; 
else (*head)++; 
} 

通話功能,

pop(&exp1.head,n); 
+0

是的!正是我想要的 – valkon

1

首先第一件事情,你缺少一個分號,裏面的union定義後struct student_or_prof

根據您的編輯#2,您應該傳遞變量的地址,將其作爲指向函數的變量的指針,然後編輯/遞增地址的內容(指針指向的變量)。如下所示:

#include <stdio.h> 

struct student_or_prof { 
    int head; 
} exp1; 

int pop(int * head, int n) { 
    if (*head == n) 
     return 1; 
    else (*head)++; 
} 

int main(){ 

    int returnval; 

    exp1.head = 5; 
    returnval = pop(&exp1.head, 10); 
    printf("%d", exp1.head); 

    getchar(); 
    return 0; 
} 

這將打印一個6。在這裏,我通過了exp1.head的地址,以便功能pop可以參考您掌握的實際exp1.head。否則,pop將只被告知exp1.head的價值,將該值複製到它自己的head變量中,隨時隨地玩。

而且,在任何情況下從pop返回一些int也是明智的。現在只有當*head == n滿意時它纔會返回一個值,並返回一些沒有意義的東西。我不認爲你想這樣,所以:

... 
else { 
    (*head)++; 
    return 0; 
} 
... 

會更好。

如果你不喜歡*head周圍的括號,那麼你可能需要使用... += 1;而不是一個後綴遞增,其中有超過了對其操作*少優先。