我試圖在多個函式之間傳遞一個指標,就像這樣:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef struct {
uint16_t w, h;
uint32_t* pixels;
} Image;
void gen_img(Image** img)
{
img->pixels = malloc(sizeof(uint32_t) * img->w * img->h); // Error by clangd: Member reference base type 'Image *' is not a structure or union
// Error by GCC: ‘*img’ is a pointer; did you mean to use ‘->’?
for (int x = 0; x < img->w; x )
for (int y = 0; y < img->h; y )
img->pixels[y * img->w x] = 0xFF000000;
}
Image* create_img(uint16_t w, uint16_t h)
{
Image* img = malloc(sizeof(Image));
img->w = w, img->h = h;
gen_img(&img);
return img;
}
int main(void)
{
Image* img = create_img(32, 32);
for (int x = 0; x < img->w; x )
for (int y = 0; y < img->h; y )
printf("%x\n", img->pixels[y * img->w x]);
return 0;
}
但是我遇到了這些我無法解釋的錯誤:
- 叮當:
Member reference base type 'Image *' is not a structure or union - 海合會:
'*img' is a pointer; did you mean to use '->'?
我做的這個例子(和指標的指標)是多次失敗嘗試的結果,肯定不是正確的方法或者我忘記了一些東西。
編輯: @user253751 的答案是正確的,但是我錯誤地復制了我的示例,所以我們無法猜測原始問題以及指標指標的原因。
出于好奇,我將一個定義為 NULL 的指標作為引數傳遞,這里是指標指標的用處。
uj5u.com熱心網友回復:
直接的問題是這*img->pixels[blah]意味著*(img->pixels[blah])優先級是錯誤的。
改為使用(*img)->pixels[blah]。
下一個問題是這段代碼沒有做你認為它做的事情。它重新分配影像而不是像素陣列。代替:
*img = malloc(sizeof(uint32_t) * w * h);
我想你的意思是:
(*img)->pixels = malloc(sizeof(uint32_t) * w * h);
// ^^^^^^^^
在這種情況下,由于*img從不改變,它不需要是一個指標到指標。您可以將指標傳遞給ImageasImage* img
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/509958.html
標籤:C指针结构
