簡體   English   中英

從結構內部的空指針訪問結構的成員

[英]access members of a structure from void pointer inside a structure

我想從結構內的void指針訪問結構的成員,我嘗試了以下代碼,但由於“((')令牌之前的預期標識符”)的錯誤,我應該在printf語句中更改什么?

#include "stdio.h"
struct
{
    int date;
    char *name;
}test;

struct
{
    void *check;
}massage;

main()
{
    test.date=21;
    test.name="Nilesh";
    massage.check =&test;
    printf("date - %d , name - %s\n",massage.((struct test *)check)->date,massage.((struct test *)check)->name);
}
struct  // anonymous struct type 
{
    int date;
    char *name;
} test;

上面的語句定義了一個匿名結構類型,並創建了一個沒有名稱的結構類型的變量test 類似地,下面的語句定義匿名結構類型,並創建一個可變massage這種類型的-

struct  // anonymous struct type
{
    void *check;
} massage;

類型轉換運算符必須在括號(type)具有(type) ,而不是變量名。 因此,必須為第一個struct命名(標記),以便使用類型轉換運算符。 另外,類型轉換運算符的結果是r-value ,因此不能與成員選擇.(dot)運算符一起使用(它應該是成員的名稱)。 因此,應在從結構中獲取值之后應用類型轉換運算符。 因此,以下表達式是錯誤的-

massage.((struct foo *)check)->date
//      |____________________|
//                |
//       this should be the member name but it
//       evaluates to a r-value - the result of
//       the typecast operator assuming struct tag
//       is foo

// it should instead be
((struct foo *)massage.check)->date
// dot operator has higher precedence than typecast
// so the struct member check is fetched first and 
// it is typecast to type (struct foo *)

我建議進行以下更改-

// standard headers should be 
// enclosed in angle < > brackets
#include <stdio.h>

// give the structure a name so it can be 
// used in typecasting
struct foo {  
    int date;
    char *name;
} test;

// anonymous struct type
struct {
    void *check;
} massage;

// return type of main should be int and 
// parameter list should contain void
int main(void) {
    test.date = 21;
    test.name = "Nilesh";
    massage.check = &test;

    // fetch the struct member check and then 
    // apply typecast operator
    printf("date - %d , name - %s\n", ((struct foo *)massage.check)->date, 
                                      ((struct foo *)massage.check)->name);
    return 0;
}

在您的表情中:

massage.((struct test *)check)->date
//               ^^^ is variable not a data-type 

有兩個錯誤:

  1. 您不能將case鍵入變量,在代碼test中變量不是類型,因此(struct test *)是錯誤的表達式。 您應該命名用戶定義的類型(如下文所建議)。

  2. 您正在應用類型轉換,而沒有訪問massage的指針成員。 因此,在表達式(struct test *)check ,實際上“ check”是未知變量。 編譯器將錯誤提示您“檢查”未聲明的變量(認為test不是數據類型,但概念上應用類型轉換的順序是錯誤的)。

我建議您進行一些更正:

  1. 命名stuct如newtype

      struct newtype // notice I given name to user defined datatype { int date; char *name; }test; 
  2. 然后按如下所示在printf函數中更正第二個和第三個參數

      ((struct newtype *)massage.check)->date // ^^^^^^^^^^^^^^ notice 

類似地,printf中的第三個參數。 首先訪問成員,然后將類型強制轉換為正確的類型。

有關完整代碼,請參考Ajay的答案

不需要結構定義-它定義了未命名結構類型的對象測試。 嘗試

struct testType
{
    int date;
    char *name;
} test;

然后轉換為(testType *)。

暫無
暫無

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

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