C中

时间:2016-07-28 14:01:30

标签: c pointers

使用邻接列表时打印顶点时遇到问题。我想只获得起始顶点,没有邻居,但我得到了他们的地址。所以,我遇到指针问题。现在我不明白为什么它没有打印正确的输出。我的代码是:

#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;

}

1 个答案:

答案 0 :(得分:1)

您的程序导致内存泄漏。您应该使用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;

}