2015-04-03 131 views
0

我有一個數組並希望將它傳遞給一個函數,該函數需要指針數組作爲參數,當我通過引用傳遞它時,它只給出第一個元素該陣列。我究竟做錯了什麼?這裏是我的代碼:無法讀取第0個元素的指針數組元素的指針

#include <stdio.h> 
#include <stdlib.h> 

struct abc{ 
    int a; 
}; 

void a(struct abc* j[]){ 
    printf("%d\n",j[1]->a); 
} 

int main() 
{ 
    struct abc* k = malloc(2 * sizeof(struct abc)); 
    k[0].a = 2; 
    k[1].a = 3; 
    a(&k); 
    return 0; 
} 

在此先感謝

+0

@BLUEPIXY thanx,this works,can you explain me why [1] - > a doesnt? – user3734435 2015-04-03 18:30:45

+0

@BLUEPIXY感謝好友解釋得好! – user3734435 2015-04-03 18:39:32

+0

@BLUEPIXY感謝夥計,我明白了,你能否讓它成爲答案,以便其他人可以更容易地找到解決方案,如果有人有問題,我有 – user3734435 2015-04-03 19:05:32

回答

0

printf("%d\n",j[1]->a);應該printf("%d\n",(*j)[1].a);

(*j)[1].a)意味着k[1].a。 (j = &k(*j)[1].a) ==>(*&k)[1].a ==>(k)[1].a

注:*j[1]裝置*(j[1])。所以*j必須括在圓括號中(如(*j))。

struct abc* j[]表示指向struct abc的指針數組。

情況下函數調用a(&k);
j的等效於僅具有一個k陣列。 (如struct abc* j[] = { k };
所以j[1]是一個無效指針的事實。

j[0]表示k因此以下是有效的。

printf("%d\n", j[0]->a);//2 
printf("%d\n", (j[0]+1)->a);//3 
3

編輯:您目前尚未建立指針數組。您目前正在創建一個結構數組。要創建一個指針數組,做這樣的事情:

#include <stdio.h> 
#include <stdlib.h> 

struct abc{ 
    int a; 
}; 

void a(struct abc* j[]){ 
    printf("%d\n",j[1]->a); 
} 

int main() 
{ 
    struct abc **k = malloc(2 * sizeof(struct abc *)); 

    k[0] = malloc(sizeof(struct abc)); 
    k[1] = malloc(sizeof(struct abc)); 
    k[0]->a = 2; 
    k[1]->a = 3; 
    a(k); 
    return 0; 
} 

老:如果你想只用結構數組做到這一點:

#include <stdio.h> 
#include <stdlib.h> 

struct abc{ 
    int a; 
}; 

void a(struct abc* j){ 
    printf("%d\n",j[1].a); 
} 

int main() 
{ 
    struct abc* k = malloc(2 * sizeof(struct abc)); 
    k[0].a = 2; 
    k[1].a = 3; 
    a(k); 
    return 0; 
} 
+0

我希望指針數組作爲函數的參數。感謝你的時間 – user3734435 2015-04-03 18:22:12

+1

@ user3734435但是你沒有一個指針數組。你有一系列的結構。如果你想傳遞一個指針數組,那麼你需要首先創建一個指針數組。 – JS1 2015-04-03 18:23:31

+0

如果我有一個函數void a(sturct abc * j [])或void a(struct abc ** j),我希望將struct abc * k傳遞給該函數呢?謝謝你 – user3734435 2015-04-03 18:26:21

1

如果你想通過數組。傳遞指針的第一個元素和元素的數量。

#include <stdio.h> 
#include <stdlib.h> 

struct abc{ 
    int a; 
}; 

void a(struct abc* j, int num){ 
    int i; 
    for(i = 0; i < num; i++) 
    { 
     printf("element %d has a value %d\n", i, j[i].a); 
    } 
} 

int main() 
{ 
    struct abc* k = malloc(2 * sizeof(struct abc)); 
    k[0].a = 2; 
    k[1].a = 3; 
    a(k, 2); 
    free(k); 
    return 0; 
} 

如果指針數組是你以後不喜歡它

#include <stdio.h> 
#include <stdlib.h> 

struct abc{ 
    int a; 
}; 

void a(struct abc** j){ 
    struct abc** tmp = j; 

    while(*tmp != NULL) 
    { 
     printf("value is %d\n", (*tmp)->a); 
     tmp++; 
    } 
} 

int main() 
{ 
    struct abc** k = malloc(3 * sizeof(struct abc*)); 
    k[0] = malloc(sizeof(struct abc)); 
    k[0]->a = 3; 
    k[1] = malloc(sizeof(struct abc)); 
    k[1]->a = 2; 
    k[2] = NULL; 
    a(k); 

    free(k[0]); 
    free(k[1]); 
    free(k); 
    return 0; 
} 
相關問題