2015-04-03 128 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; 
} 
相关问题