我有一份清单。列表的每个元素都是一个结构。
struct A
{
int size;
}
数据如下:
list[0]->size = a number.
如何指定列表中每个成员的指针?
int *p;
for(i = 0; i < listSize; i++)
{
p = &list[i];
}
由于我只分配了一个指向列表最后一个元素的指针,因此无效。我应该列出一些指针吗?
这应解决XY问题。 如何为列表中的每个元素创建指针?
编辑: 列表看起来像这样
A **list;
我想按指针排序而不是按结构排序,以便更快。
立即尝试:
A ***p = (A***) malloc(sizeof(A***));
for(i = 0; i < listLength; i++)
p[i] = &list[i];
for(i = 0; i < listLength; i++)
printf( p[i]->size); // Error.
答案 0 :(得分:1)
你可以创建指针数组:
struct A *arr_pointer[N]
struct A {
int size;
struct A *next;
};
答案 1 :(得分:0)
typedef struct {
int size;
} A, *pA;
typedef struct {
int size;
} B, *pB;
//and so on...
//Now your list can be a collection of these
typedef struct {
A a;
B b;
//additional members if defined
} LIST;
LIST list[20], *pList; //[edited to make array of LIST]
//prototype List function
LIST * updateList(LIST *a);
int main(void)
{
pList = &list[0]; //[edit to init pointer to array of lists
//access and use pointers to list as necessary
LIST *b = updateList(pList);
//Use the updated list here
printf( "b[0].a.size is: %d\n" , b[0].a.size);
printf( "b[1].a.size is: %d\n" , b[1].a.size);
printf( "b[2].a.size is: %d\n" , b[2].a.size);
printf( "b[3].b.size is: %d\n" , b[3].b.size);
printf( "b[4].b.size is: %d\n" , b[4].b.size);
printf( "b[5].b.size is: %d\n" , b[5].b.size);
return 0;
}
LIST * updateList(LIST *a)
{
//do some manipulations to LIST here...
a[0].a.size=1;
a[1].a.size=2;
a[2].a.size=3;
//and so on.
a[3].b.size=4;
a[4].b.size=5;
a[5].b.size=6;
//and so on.
return a;
}
这对你有用吗?