簡體   English   中英

將結構數組傳遞給函數?

[英]Passing an array of structs to a function?

我想學習如何通過引用將結構數組傳遞給從second function調用/執行的first function 我的目標是修改/從武斷改變結構的內容, second function 而已 下面的代碼可以正常工作,但是不幸的是,它並不能完全實現我想要的目標。 我將可以在second function訪問任意結構。 換句話說,我想處理所有的結構(使用for內環路) second function調用/執行first functionmain只有一次 ,不使用for循環。

在下面的代碼中, second function名為passByReference_inner

array_of_struct.h:

struct card
{
    int face;
    int nose;
};

typedef struct card HEAD ;

/* prototype */
extern void passByReference(HEAD **c);      /* first function */
extern void passByReference_inner(HEAD *c); /* second function */

第一個功能: (passByReference)

#include <stdio.h>
#include "array_of_struct.h"

void passByReference(HEAD **c)
{
    passByReference_inner (*c);   /* second function */
}

第二個功能: (passByReference_inner)

#include <stdio.h>
#include "array_of_struct.h"

void passByReference_inner(HEAD *c)
{
    c->face = (c->face) + 1000;
    c->nose = (c->nose) + 2000;
}

主要:

#include <stdio.h>
#include "array_of_struct.h"

int main(void)
{
    int             i;
    static HEAD     c[12];
    static HEAD *cptr[12];

    for ( i = 0; i < 12; i++ )
    {
        c[i].face = i + 30;
        c[i].nose = i + 60; 
        cptr[i]   = &c[i];
    }

    for ( i = 0; i < 12; i++ )
    {
        passByReference(&cptr[i]);  /* first function */
    }
    return 0;
}

我想你想做的是

#include <stdio.h>

struct card
{
    int face;
    int nose;
};

typedef struct card HEAD ;

/* prototype */
void passByReference(HEAD *c, int count);      /* first function */
void passByReference_inner(HEAD *c); /* second function */

void passByReference(HEAD *c, int count)
{
    int i;
    for (i = 0 ; i < count ; i++)
        passByReference_inner (&(c[i]));   /* second function */
}

void passByReference_inner(HEAD *c)
{
    c->face = (c->face) + 1000;
    c->nose = (c->nose) + 2000;
}

int main(void)
{
    int  i;
    HEAD c[12]; /* you don't need static here (do you know what static is for?) */

    for ( i = 0; i < 12; i++ )
    {
        c[i].face = i + 30;
        c[i].nose = i + 60;
    }
    /* 
     * the element count of the array is sizeof(c) / sizeof(c[0]) 
     *    (totalSizeOfArray) / (indivudualElementSizeOfArray).
     */
    passByReference(c, sizeof(c) / sizeof(c[0]));  /* first function */

    return 0;
}

您應該知道的是, c中的數組在作為參數傳遞給函數時會衰減為指向其第一個元素的指針。

因為您要處理第二個函數中的所有結構,所以我看不到第一個函數的需要,反正這就是您的處理方式

#include <stdio.h>

struct card
{
    int face;
    int nose;
};

typedef struct card HEAD ;

/* prototype */
void passByReference(HEAD *const c, int count);      /* first function */
void passByReference_inner(HEAD *const c, int count); /* second function */

void passByReference(HEAD *const c, int count)
{
    passByReference_inner(c, count);   /* second function */
}

/* HEAD *const c prevents the pointer c to be changed
 * this way it will never point anywhere else.
 *
 * And you can be sure to alter the original data.
 */
void passByReference_inner(HEAD *const c, int count)
{
    for (int i = 0 ; i < count ; ++i)
    {
        c[i].face = (c[i].face) + 1000;
        c[i].nose = (c[i].nose) + 2000;
    }
}

int main(void)
{
    int  i;
    HEAD c[12]; /* you don't need static here (do you know what static is for?) */

    for ( i = 0; i < 12; i++ )
    {
        c[i].face = i + 30;
        c[i].nose = i + 60;
    }
    /* 
     * the element count of the array is sizeof(c) / sizeof(c[0]) 
     *    (totalSizeOfArray) / (indivudualElementSizeOfArray).
     */
    passByReference(c, sizeof(c) / sizeof(c[0]));  /* first function */

    return 0;
}

由於您實際上是在傳遞指針,因此您可以直接在第一個和第二個函數中直接更改其內容。

還有一件事,您實際上並不需要static關鍵字,特別是在main()static保留函數調用之間的變量值,並且由於main()通常在程序生命周期中僅被調用一次。 。在那兒使用static沒有多大意義。

您的第二個功能是正確的。

指向數組第一個元素的指針實際上與指向數組本身的指針相同。

你應該做的是

void passByReference_inner(HEAD *c, size_t n)
{
}

因此,您將把指針傳遞給數組的第一個元素以及數組中的元素數,如下所示:

passByReference(c, sizeof(c)/sizeof(c[0]));

這會將指針傳遞到c數組的第一個元素,並將數組中的元素數傳遞給passByReference_inner()。 sizeof(c)是整個數組的大小(以字節為單位)。 sizeof(c [0])是數組中元素的大小。 因此,例如,如果每個結構的長度為10個字節(僅作為示例),而您有12個結構的數組,則整個數組的大小為120個字節,這將計算出值120/10 = 12,則數組中元素的數量,自動。

當您使用數組對象的名稱時,在C / C ++中,它會自動成為指向數組第一個元素的指針。

在函數中,可以按以下方式使用數組:

void passByReference_inner(HEAD *c, size_t n)
{
    for (size_t i=0; i<n; i++)
    {
        HEAD *p=c+i;

        // p is now a pointer to the ith element of the array
    }
}

向指針添加整數n會使指針前進到數組的下一個nth元素。 向指針添加整數值不會使指針超前此字節數,而是指針所指向的對象中的字節數乘以您要添加(或減去,等於)的數字。 這使指針算法可以正確地執行操作。

  • 以下代碼可以干凈地編譯。
  • 以下代碼移動了增量值循環
    到passByReference()函數內部。

/* 
 * Note: guard code is used in a header file
 *       so the header file can only be included once
 *       in each compilation unit 
 */

// note the inclusion of a 'guard' wrapper
// begin: array_of_struct.h file
#ifndef ARRAY_OF_STRUCT_H
#define ARRAY_OF_STRUCT_H

struct card
{
    int face;
    int nose;
};

// dont obsecure the code with useless typedef statements
//typedef struct card HEAD ;

#define MAX_CARDS (12)

/* prototype */
extern void passByReference(struct card *pCards);      /* first function */
extern void passByReference_inner(struct card *pCard); /* second function */
#endif
// end: array_of_struct.h


//first function: (passByReference), in different file

#include <stdio.h>
#include "array_of_struct.h" 

void passByReference(struct card *pCards)
{
    int i=0; // loop index

    for(i=0;i<MAX_CARDS;i++)
    {
        passByReference_inner (&pCards[i]);   /* second function */
    } // end for
} // end function: passByReference

// second function: (passByReference_inner), in different file

#include <stdio.h>
#include "array_of_struct.h"

void passByReference_inner(struct card *pCard)
{
    pCard->face = (pCard->face) + 1000;
    pCard->nose = (pCard->nose) + 2000;
} // end function: passByReference_inner

//main, in a different file

#include <stdio.h>
#include "array_of_struct.h"

int main()
{
    int i = 0; // loop index
    static struct card     cards[MAX_CARDS];

    for ( i = 0; i < MAX_CARDS; i++ )
    {
        cards[i].face = i + 30;
        cards[i].nose = i + 60;
    } // end for

    passByReference(&cards[0]);  /* first function gets ptr to whole array*/
    // could also be written as:
    // passByReference(cards);

    return 0;
} // end function: main

我分析了所有三個解決方案(iharob,user3629249,Sam Varshavchik),得出的結論是,Sam Varshavchik和iharob的第二個解決方案確實物有所值。 本質上,第一個iharob的解決方案和user3629249解決方案是相等的。 他們從main轉到第first function for循環。 iharob帖子的第二個解決方案符合初始帖子的要求。 山姆的解決方案給了我足夠的提示/指令“如何移動for循環從主到second function (這是,基本上,我不知道如何做到這一點,因此要求幫助)。

因此,總而言之,這是實現幾乎所有貢獻者的所有建議的源代碼。 該代碼可以干凈地編譯,因此像我這樣的初學者可以直接使用它,並學到一些有關指針的指針,指針算術以及結構數組的詳細信息。

array_of_struct.h (頭文件)

#ifndef ARRAY_OF_STRUCT_H
#define ARRAY_OF_STRUCT_H

/* HEAD structure definition */
typedef struct
{
    int face;
    int nose;
} HEAD;       // end structure HEAD

#define MAX_HEADS (12)

/* prototype */
extern void passByReference(HEAD **c, size_t n);
extern void passByReference_inner(HEAD *c, size_t n);

#endif

passByReference.c (第一個函數)

#include <stdio.h>
#include "array_of_struct.h"

void passByReference(HEAD **c, size_t n)
{
    passByReference_inner (*c, n);
}

passByReference_inner.c (第二個功能)

#include <stdio.h>
#include "array_of_struct.h"

void passByReference_inner(HEAD *c, size_t n)
{
    int   i;
    HEAD *p;

    printf("\nPOINTER ARITHMETIC: The value of struct's  members after PASS BY REFERENCE \n");
    for ( i = 0; i < n; i++ )
    {
        p = c + i;

        p->face = (p->face) + 1000;
        p->nose = (p->nose) + 2000;
        printf("struct[%i].face = %d  \n",i, p[0].face);
        printf("struct[%i].nose = %d  \n",i, p[0].nose);
    }

    printf("\nARRAY INDEX MATH: The value of struct's  members after PASS BY REFERENCE\n");
    printf("[NOTE: structs were updated in the for loop above]\n");
    for ( i = 0; i < n; i++ )
    {
        printf("struct[%i].face = %d  \n",i, c[i].face);
        printf("struct[%i].nose = %d  \n",i, c[i].nose);
    }
}

main.c中

#include <stdio.h>
#include "array_of_struct.h"

int main(void)
{
    int     i;
    HEAD    c[MAX_HEADS];
    HEAD   *cptr;
    size_t  n;

    n = (sizeof(c) / sizeof(c[0]);

    printf("\nINITIALIZATION of all struct's  members\n");
    for ( i = 0; i < n; i++ )
    {
        c[i].face = i + 30;
        c[i].nose = i + 60; 
        printf("struct[%i].face = %d\n",i, c[i].face);
        printf("struct[%i].nose = %d\n",i, c[i].nose);
    }

    cptr = &c[0];
    passByReference(&cptr, n); 

    return 0;
}

暫無
暫無

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

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