使用邻接表时,在打印顶点时遇到问题。我只想得到起始顶点,而没有邻居,但是我要得到它们的地址。因此,我在使用指针时遇到了问题。现在我不明白为什么它不能打印正确的输出。我的代码是:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct ADI{
int val;
struct ADI *urm;
}ADI;
ADI *adjancencyList( int vertex )
{
int neigh,i;
ADI *head, *elem, *vec;
head = ( ADI* ) malloc( sizeof( ADI ) );
head->val = vertex;
elem = head;
printf( "Input number of neighbours:" );
scanf( "%d", &neigh );
for( i = 0; i < neigh ; i++)
{ printf( "Neighbour:" );
vec = ( ADI* ) malloc( sizeof( ADI ) );
elem->urm = vec;
scanf( "%d", &elem->val );
}
return head;
}
int main()
{ int i, n, v;
printf("Input number of vertices ");
scanf( "%d", &n );
ADI *A = ( ADI* ) malloc( n * sizeof( ADI ) );
for( i = 0; i < n; i++ )
{
printf( "Input vertex name:" );
scanf( " %d ", &v );
A = adjancencyList( v );
A++;
}
A = &( A[0] );
for( i = 0; i < n; i++ )
{
printf(" %d ", A->val );
printf( " \n " );
A++;
}
return 0;
}
最佳答案
您的程序导致内存泄漏。您应该使用ADI*
的数组而不是ADI
的数组来存储从adjancencyList()
返回的内容。在这种情况下,使用下标看上去比增加要好。还有一个技巧是A = &( A[0] );
实际上什么也不做。
另请注意,他们说you shouldn't cast the result of malloc()
in C。
尝试这个:
int main(void)
{
int i, n, v;
printf("Input number of vertices ");
scanf( "%d", &n );
ADI **A = malloc( n * sizeof( ADI* ) );
for( i = 0; i < n; i++ )
{
printf( "Input vertex name:" );
scanf( " %d ", &v );
A[i] = adjancencyList( v );
}
for( i = 0; i < n; i++ )
{
printf(" %d ", A[i]->val );
printf( " \n " );
}
return 0;
}