Почему функция printf не печатает значение списка, который я хочу напечатать? - PullRequest
0 голосов
/ 17 ноября 2018

Мне не удается распечатать значение данных первого узла. Может ли кто-нибудь показать мне, что я делаю не так?

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


typedef struct S_node{

  int data;
  struct S_node *next;

} node;


int main () {

  node* first; 

  first->data = 7;
  first->next = NULL;

  printf("\nData: %d", first->data);

}

Я обновил свой код:

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


typedef struct S_node{

  int data;
  struct S_node *next;

} node;

void PrintList(node* start);

int main () {

  node* first = malloc(sizeof(node));
  node* second = malloc(sizeof(node));
  node* third = malloc(sizeof(node));

  first->data = 7;
  first->next = second;

  second->data = 6;
  second->next = third;

  third->data = 5;
  third->next = NULL;

  PrintList(first);

  free(first);
  free(second);
  free(third);
}

void PrintList(node* start) {

node* currentNode = start;
while(currentNode =! NULL) {
    printf("Data: %d", currentNode->data);
    currentNode = currentNode->next;
}
}

Я пытаюсь распечатать данные от первого до последнего узла, все еще получая предупреждение «назначение из несовместимого типа указателя» при выполнении

first->next = second;

и

second->next = third;

Когда я запускаю программу, ничего не печатается.

Ответы [ 2 ]

0 голосов
/ 17 ноября 2018
int main () {

  node* first = NULL;           // Be Explicit that the pointer is not yet valid.
  first = malloc(sizeof(node)); // Now there is memory attached to the pointer.

  first->data = 7;
  first->next = NULL;

  printf("\nData: %d", first->data);

  free(first);  // Release the memory when done.
  first = NULL; // Prevent accidental re-use of free'd memory

}
0 голосов
/ 17 ноября 2018

когда вы получили указатель типа

node* first

Вы должны специализировать указатель на какой адрес.malloc мы можем получить динамическое пространство в памяти и назначить адрес указателю.

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


typedef struct S_node {

    int data;
    struct S_node *next;

} node;


int main() {

    node* first = malloc(sizeof(node));

    first->data = 7;
    first->next = NULL;

    printf("\nData: %d", first->data);

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...