запрос на членство "далее" в чем-то не являющемся структурой или объединением


Почему я получаю эту ошибку?:

request for member 'next' in something not a structure or union|

В этих строках:

 if(*head->next == NULL){
        *head->next = newNode;

Ошибка :

||=== Build: Debug in Lab9 (compiler: GNU GCC Compiler) ===|
C:Users\C_ProjectsLab9main.c||In function 'insertNode':|
C:Users\C_ProjectsLab9main.c|38|error: request for member 'next' in something not a structure or union|
C:UserssC_ProjectsLab9main.c|39|error: request for member 'next' in something not a structure or union|
C:Users\C_ProjectsLab9main.c|44|error: request for member 'next' in something not a structure or union|
C:Users\C_ProjectsLab9main.c|48|warning: assignment from incompatible pointer type [enabled by default]|
C:Users\C_ProjectsLab9main.c|50|warning: assignment from incompatible pointer type [enabled by default]|
C:Users\C_ProjectsLab9main.c|51|warning: assignment from incompatible pointer type [enabled by default]|
C:Users\C_ProjectsLab9main.c|56|warning: return type defaults to 'int' [-Wreturn-type]|
C:Users\C_ProjectsLab9main.c||In function 'printList':|
C:Users\C_ProjectsLab9main.c|58|error: request for member 'next' in something not a structure or union|
C:Users\C_ProjectsLab9main.c|63|error: request for member 'next' in something not a structure or union|
C:Users\C_ProjectsLab9main.c|65|warning: implicit declaration of function 'print' [-Wimplicit-function-declaration]|
C:Users\C_ProjectsLab9main.c|65|error: expected ')' before 'current'|
C:Users\C_ProjectsLab9main.c|66|warning: assignment from incompatible pointer type [enabled by default]|
C:Usersshohi_000C_ProjectsLab9main.c|72|warning: return type defaults to 'int' [-Wreturn-type]|
C:Users\C_ProjectsLab9main.c||In function 'deleteList':|
C:Users\C_ProjectsLab9main.c|74|error: request for member 'next' in something not a structure or union|
C:Users\C_ProjectsLab9main.c|74|error: expected statement before ')' token|
C:Users\C_ProjectsLab9main.c|79|error: 'else' without a previous 'if'|
C:Users\C_ProjectsLab9main.c|80|error: request for member 'next' in something not a structure or union|
C:Users\C_ProjectsLab9main.c|83|warning: assignment from incompatible pointer type [enabled by default]|
C:Users\C_ProjectsLab9main.c||In function 'main':|
C:Users\C_ProjectsLab9main.c|98|warning: initialization makes integer from pointer without a cast [enabled by default]|
C:Users\C_ProjectsLab9main.c|99|warning: initialization makes integer from pointer without a cast [enabled by default]|
C:Users\C_ProjectsLab9main.c|101|warning: initialization makes integer from pointer without a cast [enabled by default]|
C:Users\C_ProjectsLab9main.c|101|warning: unused variable 'maxValue' [-Wunused-variable]|
C:Users\C_ProjectsLab9main.c|98|warning: unused variable 'seedNum' [-Wunused-variable]|
C:Users\C_ProjectsLab9main.c||In function 'printList':|
C:Users\C_ProjectsLab9main.c|69|warning: control reaches end of non-void function [-Wreturn-type]|
||=== Build failed: 10 error(s), 14 warning(s) (0 minute(s), 0 second(s)) ===|

Код

//Defines the struct of Node
typedef struct NodeStruct{
    int data;
    struct Node *next;
}Node;
//The function insert a newly created Node into its proper position
//The list will be sorted in ascending order
void insertNode(Node **head, int data){
    //Create a new Node with the given num
    Node *newNode = (Node *)malloc(sizeof(Node));
    newNode->data = data;

    //Check if the list is empty
    if(*head->next == NULL){
        *head->next = newNode; //point head's next to the newNode
        newNode->next = NULL;
    }
    //If the list is not empty, then insert the newNode into its proper position
    else{
        Node *current = *head->next; //starts from the very first element(after dummy node!)
        Node *previous = NULL; //previous is needed for storing the previous node before exiting the loop
        while(current != NULL && current->data < data){
            previous = current;
            current = current->next;
        }
        previous->next = newNode; //place the node between previous and current
        newNode->next = current;
    }
}
int main(int argc, char *argv[])
{
    //If argc < 4 then quit the program
    if(argc < 4){
        badProgram();
    }
    else{
        Node *head = dummyNode();
        int seedNum = argv[1]; //gets the integer for seeding the random generator
        int totalNums = argv[2]; //gets the total number of random numbers
        srand(totalNums); //input into the srand()
        int maxValue = argv[3]; //maximum possible value

        int i;
        for(i = 0; i < totalNums; i++){
            int num = rand(); //generates a random number
            fprintf(stdout, "%d", num); //outputs the number to the screen
            insertNode(&head, num);
        }
    }


    return 0;
}
3 2

3 ответа:

#include<stdio.h>
#include<stdlib.h>
typedef struct NodeStruct{
    int data;
    struct Node *next;
}Node;
//The function insert a newly created Node into its proper position
//The list will be sorted in ascending order
void insertNode(Node **head, int data){
    //Create a new Node with the given num
    Node *newNode = (Node *)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next=NULL;
    //Check if the list is empty
    if(head == NULL){
        head = newNode; //point head's next to the newNode
       // head->next = NULL;
    }
    //If the list is not empty, then insert the newNode into its proper position
    else{
        Node *current = head; //starts from the very first element(after dummy node!)
        Node *previous = NULL; //previous is needed for storing the previous node before exiting the loop
        while(current != NULL && current->data < data){
            previous = current;
            current = current->next;
        }
        previous->next = newNode; //place the node between previous and current
        newNode->next = current;
    }
}
int main(int argc, char *argv[])
{
    //If argc < 4 then quit the program
    if(argc < 4){
        badProgram();
    }
    else{
        Node *head = dummyNode();
        int seedNum = argv[1]; //gets the integer for seeding the random generator
        int totalNums = argv[2]; //gets the total number of random numbers
        srand(totalNums); //input into the srand()
        int maxValue = argv[3]; //maximum possible value

        int i;
        for(i = 0; i < totalNums; i++){
            int num = rand(); //generates a random number
            fprintf(stdout, "%d", num); //outputs the number to the screen
            insertNode(&head, num);
        }
    }


    return 0;
}

В вашем коде возникли некоторые проблемы во-первых: head уже является узлом указателя, который должен указывать на первый узел, как показано ниже


|голова|-->firstNode-->secondNode , и так далее

Но, из приведенного ниже фрагмента кода

if(*head->next == NULL){
        *head->next = newNode; //point head's next to the newNode
        newNode->next = NULL;
    }


Я вижу, что происходит что-то еще, вы пытаетесь сохранить адрес newNode в адрес головы**(не адрес, который хранит голова). Адрес руководителя таков: фактически хранится без переменной. **Это может быть основной причиной того, что вы получаете ошибку
Надеюсь, я исправил код от его синтаксических ошибок, но методы, возможно, имеют некоторую неопределенную ссылку. Может быть, вы где-то определили метод. Надеюсь, вы поняли ответ

Спасибо

Это имеет отношение к следующему:

**head

Затем вы делаете это

*head->next

Вы все еще указываете на указатель, который указывает на голову.

Вот полный код:

void insertNode(Node *head, int data){
    //Create a new Node with the given num
    Node *newNode = malloc(sizeof(Node));
    newNode->data = data;

    //Check if the list is empty
    if(head->next == NULL){
        head->next = newNode; //point head's next to the newNode
        newNode->next = NULL;
    }
    //If the list is not empty, then insert the newNode into its proper position
    else{
        Node *current = head->next; //starts from the very first element(after dummy node!)
        Node *previous = NULL; //previous is needed for storing the previous node before exiting the loop
        while(current != NULL && current->data < data){
            previous = current;
            current = current->next;
        }
        previous->next = newNode; //place the node between previous and current
        newNode->next = current;
    }
}

Ваша функция должна быть просто

void insertNode(Node *head, int data)

Проблема заключается в выражении *head->next. Поскольку -> имеет более высокий приоритет, чем *, это эквивалентно *(head->next). Вы хотите (*head)->next, поэтому вам нужны скобки.