簡體   English   中英

使用 C 中的指針運算符將結構傳遞給函數

[英]Passing structs to a function using the pointer operator in C

在這段代碼中:

我擁有的結構有 2 個成員,並且定義了 3 個變量。

其中兩個的值由我分配,第三個應該來自一個函數。

編碼:

#include <stdio.h>

#include <stddef.h>
typedef unsigned short      int u16;        /*2 byte unsigned int*/
typedef unsigned char            u8;        /*1 byte unsigned char*/



typedef struct 
{
    u8 id;
    u8 salary;
} Emp;
void Math (Emp *Ptr1, Emp *Ptr2, Emp *resPtr);



void main ()
{
    Emp Ahmed = {100, 100};
    Emp Ali = {200, 200};
    
    Emp Result = {0,0};
    
    Math (&Ahmed, &Ali, &Result);
    printf("%d\n%d\n", Result.id, Result.salary);   
    
}


void Math (Emp *Ptr1, Emp *Ptr2, Emp *resPtr)
{
    resPtr -> id = Ptr1 -> id + Ptr2 -> id;
    resPtr -> salary = Ptr1 -> salary + Ptr2 -> salary;
}

結果是:

44
44

我正在使用 gcc 工具鏈,我到底哪里出錯了?

一個unsigned char只能保存 255 大的值。分配一個更大的值會導致它被有效地截斷到最低的 8 位。

將成員的數據類型更改為unsigned short 然后他們將能夠保持結果。

而不是手動聲明這些 typedef(s)

typedef unsigned short      int u16;        /*2 byte unsigned int*/
typedef unsigned char            u8;        /*1 byte unsigned char

您應該在存在類似聲明的地方包含標准頭文件stdint.h

此外,您的程序中甚至不使用第一個 typedef。

unsigned char類型對象的最大值定義為(C 標准)

— unsigned char 類型對象的最大值

UCHAR_MAX 255 // 28 − 1

因此,如果將100200相加,則結果將被截斷為44

因此,您應該至少使用unsigned short類型而不是unsigned char

此外,由於前兩個參數在函數內未更改,因此應使用限定符const聲明它們。

這是一個演示程序。

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

typedef struct 
{
    uint16_t id;
    uint16_t salary;
} Emp;

void Math( const Emp *Ptr1, const Emp *Ptr2, Emp *resPtr );

int main(void) 
{
    Emp Ahmed = { .id = 100, .salary = 100 };
    Emp Ali   = { .id = 200, .salary = 200 };
    
    Emp Result = { .id = 0, .salary = 0 };
    
    Math( &Ahmed, &Ali, &Result );

    printf("%" PRIu16 "\t%" PRIu16 "\n", Result.id, Result.salary ); 

    return 0;
}

void Math( const Emp *Ptr1, const Emp *Ptr2, Emp *resPtr )
{
    resPtr -> id = Ptr1 -> id + Ptr2 -> id;
    resPtr -> salary = Ptr1 -> salary + Ptr2 -> salary;
}

程序輸出是

300 300

暫無
暫無

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

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