我正在做一個小練習,將一個指標陣列(雙指標)加載到一個結構中。我在頭檔案中有如下的定義:
#include <stdio.h>/span>
#define LEN(5)
typedef struct sample_s {
int num;
char *name;
}sample_t;
typedef struct new_sample_s {
char *string。
sample_t **sample_arr;
}new_sample_t;
sample_t table[LEN] = {
{0, "eel"},
{1, "salmon"] 。
{2, "cod"},
{3, "tuna"},
{4, "catfish"}.
};
和使用定義int這個.c檔案:
#include "test.h"
void print_new_sample_array(sample_t **sample_arr) {
int len = sizeof(table)/sizeof(new_sample_t)。
for(int i = 0; i < len; i ){
printf("The array element is: %s
", sample_arr[i]->name)。)
}
}
int main() {
new_sample_t new_sample。
new_sample.sample_arr = table;
print_new_sample_array(new_sample.sample_arr)。
return 0;
}
我有兩個問題:
首先我不確定如何正確地將table加載到new_sample.sample_arr中。
這里的錯誤資訊:
test.c: 在函式'main'中。
test.c:13:27: warning: 從不兼容的指標型別賦值 [-Wincompatible-pointer-types]
new_sample.sample_arr = table;
^
其次,我不確定我如何能夠參考sample_arr中每個元素的屬性。例如,當我做下面的事情時,程式出錯了:
for(int i = 0; i < LEN; i ){
printf("This is the elem in the array: %s", new_sample[i]-> name);
}
我想了解更多關于雙指標的概念以及為什么我做錯了。我真的很感謝你的回答,使sample_arr成為雙指標
謝謝你!
uj5u.com熱心網友回復:
在這個賦值陳述句中
new_sample.sample_arr = table;
右邊的運算元(在陣列隱式轉換為指向其第一個元素的指標后)的型別為sample_t *,而左邊的運算元的型別為sample_t **,這是由于資料成員的宣告所致
sample_t **sample_arr;
沒有從型別sample_t *到型別sample_t **的隱式轉換。所以編譯器發出了一條資訊。
你應該宣告這個資料型別。
你應該像
那樣宣告資料成員sample_t *sample_arr。
而相應地,函式宣告將看起來像
void print_new_sample_array(sample_t *sample_arr)。
而在這個函式中,對printf的呼叫將看起來像
printf("The array element is: %s
", sample_arr[i].name)。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/322411.html
標籤:
