C 链表指针问题

C 链表指针问题,c,C,我不知道这为什么不起作用 #include <stdio.h> #include <stdlib.h> #include <time.h> // struct of list typedef struct noeud { int adresse, taille, temp; struct noeud* suivant; } * liste; int random(int a, int b) { return (a + (rand(

我不知道这为什么不起作用

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

// struct of list
typedef struct noeud
{
    int adresse, taille, temp;
    struct noeud* suivant;

} * liste;

int random(int a, int b)
{
    return (a + (rand() % ((b + 1) + a)));
}

void initialisation(liste* LBO)
{
    *LBO = NULL;
}

有几个问题:

而不是打电话

 initialisation(&LBO);
这并不是真的错,只要写下:

LBO = NULL;
然后不要用
typedef
s隐藏指针,这只会增加混淆

而不是:

typedef struct noeud
{
  int adresse, taille, temp;
  struct noeud* suivant;

} *liste;
写:

struct noeud
{
  int adresse, taille, temp;
  struct noeud* suivant;    
};
并使用
struct noeud*
而不是
liste

现在真正的问题是:

这是错误的。这里为指针分配大小,但需要为整个结构分配大小:

q = malloc(sizeof(liste));
这实际上与:

q = malloc(sizeof(struct noeud*))
但你需要:

q = malloc(sizeof(struct noeud))
现在您知道为什么用typedefs隐藏指针是个坏主意了

下面是您的程序的正确版本(
#include
s,为简洁起见):

struct noeud
{
内部地址,泰勒,温度;
结构noeud*suivant;
};
int随机(int a,int b)
{
返回值(a+(rand()%((b+1)+a));
}
无效创建(结构noeud**LBO)
{
结构noeud*q,*prec=NULL;
int i=0;

//srand(时间(空));这需要一些认真的编辑。我尝试过,但放弃了。尝试使用调试器查找问题的原因。要解决问题,您首先需要知道它是什么…以及您的程序应该做什么?@unwind Done,file style:p。这就是在代码中使用非英语标识符的问题。现在,它大大减少了代码的数量那些一眼就能看懂的人。哦,不要把指针藏在typedef后面,那会让人产生无尽的困惑。
q = malloc(sizeof(struct noeud))
struct noeud
{
  int adresse, taille, temp;
  struct noeud* suivant;
};

int random(int a, int b)
{
  return (a + (rand() % ((b + 1) + a)));
}

void creation(struct noeud** LBO)
{
  struct noeud* q, *prec = NULL;
  int i = 0;
  // srand(time(NULL));  <<<<< don't call srand here, call it once at the 
                            // beginning of the program
  while (i < 3)
  {
    printf("%d", i);
    q = malloc(sizeof(struct noeud));

    if (*LBO == NULL)
    {
      q->adresse = 0;
      q->taille = random(5, 45);
      q->temp = random(5, 15);
      q->suivant = *LBO;
      *LBO = q;
      i++;
    }
    else
    {
      prec = *LBO;
      q->taille = random(5, 45);
      q->temp = random(5, 15);
      q->adresse = prec->adresse + prec->taille;
      q->suivant = *LBO;
      *LBO = q;
      i++;
    }
  }
}

void affichage(struct noeud* LBO)
{
  printf("\nvoici ta struct noeud* \n ");
  while (LBO != NULL)
  {
    printf("%d-->", LBO->taille);
    LBO = LBO->suivant;
  }
  // if (LBO == NULL)  <<<<<<<<<<< drop this, LBO is always NULL here
                                // but it doesn't hurt, it's just useless
    printf("NULL");
}

int main()
{
  srand(time(NULL));   // <<<<<<<<<<<<< call srand here
  struct noeud* LBO;
  LBO = NULL;

  creation(&LBO);

  affichage(LBO);
  return 0;
}