簡體   English   中英

在函數中傳遞結構成員

[英]Passing Struct members in Functions

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

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;

用變量而不是結構變量傳遞其成員

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

因為我不想只將函數用於結構。 可能嗎?

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

EDIT_2我也知道這個pop(exp1.head,n)是可行的,但是我也希望exp1.head在函數pop結束后進行更改。

使用指針。 將poniter傳遞給exp1.head並通過在函數中取消引用它來對其進行操作,

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

調用函數為

pop(&exp1.head,n);

首先,在struct student_or_profunion定義之后,您缺少了分號。

按照您的編輯#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的值, exp1.head將該值復制到其自己的head變量中,然后進行操作。

而且,在任何情況下都應該從pop中返回一些int是明智的。 現在,僅當滿足*head == n時,它才返回一個值,並返回沒有意義的值。 我認為您不想要這樣,所以:

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

會更好。

如果您不喜歡*head周圍的括號,那么您可能要使用... += 1; 而不是后綴增量,后者比解引用運算符*優先級低。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM