簡體   English   中英

C 指針 - 作為數組的結構

[英]C Pointers - Structs that are arrays

我已經研究這段代碼幾個小時了,我很困惑為什么 printf 只打印垃圾,我是堆棧溢出的新手,對 C 相當陌生,所以請原諒我在這篇文章中的任何錯誤。 我研究了指向數組結構的指針,但找不到任何有用的東西。

typedef struct my
{
    int x;
    int y;
} My;

My * main2(void);

void show(void)
{
    My * m = main2();

    printf("%u\n", m);

    printf("%u\n", m);
    printf("%d\n", m->x);
    printf("%d\n", m->y);
    m++;
    printf("%u\n", m);
    printf("%d\n", m->x);
    printf("%d\n", m->y);
    m++;
    printf("%u\n", m);
    printf("%d\n", m->x);
    printf("%d\n", m->y);
}

My * main2(void)
{
    My j[3];
    j[0].x = 2;
    j[0].y = 4;

    j[1].x = 3;
    j[1].y = 5;

    j[2].x = 7;
    j[2].y = 9;

    printf("%u\n", j);
    return j;
}

int main()
{
    show();

    return 0;
}

在函數內定義的變量只有該函數的生命周期。 一旦函數返回,變量本質上就不存在了。

現在,如果您返回一個指向此類變量(或像您一樣指向數組的第一個元素)的指針並且該數據不再存在,那么當您嘗試使用該指針時,您會得到未定義的行為

解決此類問題的一種方法是將數組(或再次指向其第一個元素的指針)作為參數傳遞給函數:

void main2(My *j)
{
    j[0].x = 2;
    // And so on...
}

並且要將數組傳遞給函數,請記住,當在需要指針的上下文中使用時,數組會衰減為指向其第一個元素的指針。

這意味着您可以像傳遞任何其他變量一樣傳遞它:

My arr[3];
main2(arr);  // equal to main2(&arr[0]);

另一方面,使用printf打印指針的格式是"%p" 指針也需要轉換為void *

printf("%p\n", (void *) j);

為什么 printf 只打印垃圾? 這是因為你在這里返回了一個局部變量的地址

My j[3];
...
...
return j; /* j is a local array, its scope is within this this function not outside */

你的編譯器可能會像這樣警告你

函數返回局部變量的地址 [-Werror=return-local-addr]

為了克服這個問題,您可以創建動態數組並返回它。

同樣在打印m結構指針時,使用%p而不是%u格式說明符。 例如

printf("%p\n", (void*)m);

好的,我得到了答案,我忘記了這一點非常重要,在函數返回后,函數中的所有內容都“消失了”,謝謝兩位幫助回答這個問題的人:)

typedef struct my
{
    int x;
    int y;
} My;

void getData(My * pos)
{
    printf("%d", pos->x);
    printf("%d", pos->y);
    pos++;
    printf("%d", pos->x);
    printf("%d", pos->y);
}

int main()
{
    My x[2];

    x[0].x = 3;
    x[0].y = 4;

    x[1].x = 5;
    x[1].y = 6;

    getData(x);

    return 0;
}

暫無
暫無

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

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