天天看點

c 數組指針使用

長時間不用c基礎代碼,導緻有些基礎文法忘記了,今天抽空寫個小demo回顧下

#include <cstdio>
#include "main.h"
typedef struct
{
    int a; 
    int b; 
}obj;

//
void func(obj* pInfo)
{
    int m = pInfo->a;

    int n = pInfo[0].a;//此寫法與上面寫法相同

    printf("%d,%d\n", m, n);
}
void func1(obj(*pInfo)[10] )
{
    for (int i = 0; i < 10; i++)
    {
        (*pInfo)[i].a = 10;
        (*pInfo)[i].b = 11;
        

        pInfo[0][i].a = 10;//此寫法與上面寫法相同
        pInfo[0][i].b = 11;
    }
}
int main()
{
    //對象指針
    obj slaveInfo;
    slaveInfo.a = 10;
    slaveInfo.b = 11;
    func(&slaveInfo);

    //對象數組指針
    obj slaveInfos[10];
    func1(&slaveInfos);
    
    for (int i = 0; i < 10; i++)
    {
        printf("%d,=%d\n", i,slaveInfos[i].a);
    }
    return 0;
}
      

執行結果:

c 數組指針使用