Запрос на членство `` next'` в чем-то не структура или объединение
Почему я получаю эту ошибку?:
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_Projects\Lab9\main.c||In function 'insertNode':|
C:\Users\\C_Projects\Lab9\main.c|38|error: request for member 'next' in something not a structure or union|
C:\Users\s\C_Projects\Lab9\main.c|39|error: request for member 'next' in something not a structure or union|
C:\Users\\C_Projects\Lab9\main.c|44|error: request for member 'next' in something not a structure or union|
C:\Users\\C_Projects\Lab9\main.c|48|warning: assignment from incompatible pointer type [enabled by default]|
C:\Users\\C_Projects\Lab9\main.c|50|warning: assignment from incompatible pointer type [enabled by default]|
C:\Users\\C_Projects\Lab9\main.c|51|warning: assignment from incompatible pointer type [enabled by default]|
C:\Users\\C_Projects\Lab9\main.c|56|warning: return type defaults to 'int' [-Wreturn-type]|
C:\Users\\C_Projects\Lab9\main.c||In function 'printList':|
C:\Users\\C_Projects\Lab9\main.c|58|error: request for member 'next' in something not a structure or union|
C:\Users\\C_Projects\Lab9\main.c|63|error: request for member 'next' in something not a structure or union|
C:\Users\\C_Projects\Lab9\main.c|65|warning: implicit declaration of function 'print' [-Wimplicit-function-declaration]|
C:\Users\\C_Projects\Lab9\main.c|65|error: expected ')' before 'current'|
C:\Users\\C_Projects\Lab9\main.c|66|warning: assignment from incompatible pointer type [enabled by default]|
C:\Users\shohi_000\C_Projects\Lab9\main.c|72|warning: return type defaults to 'int' [-Wreturn-type]|
C:\Users\\C_Projects\Lab9\main.c||In function 'deleteList':|
C:\Users\\C_Projects\Lab9\main.c|74|error: request for member 'next' in something not a structure or union|
C:\Users\\C_Projects\Lab9\main.c|74|error: expected statement before ')' token|
C:\Users\\C_Projects\Lab9\main.c|79|error: 'else' without a previous 'if'|
C:\Users\\C_Projects\Lab9\main.c|80|error: request for member 'next' in something not a structure or union|
C:\Users\\C_Projects\Lab9\main.c|83|warning: assignment from incompatible pointer type [enabled by default]|
C:\Users\\C_Projects\Lab9\main.c||In function 'main':|
C:\Users\\C_Projects\Lab9\main.c|98|warning: initialization makes integer from pointer without a cast [enabled by default]|
C:\Users\\C_Projects\Lab9\main.c|99|warning: initialization makes integer from pointer without a cast [enabled by default]|
C:\Users\\C_Projects\Lab9\main.c|101|warning: initialization makes integer from pointer without a cast [enabled by default]|
C:\Users\\C_Projects\Lab9\main.c|101|warning: unused variable 'maxValue' [-Wunused-variable]|
C:\Users\\C_Projects\Lab9\main.c|98|warning: unused variable 'seedNum' [-Wunused-variable]|
C:\Users\\C_Projects\Lab9\main.c||In function 'printList':|
C:\Users\\C_Projects\Lab9\main.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 ответа
#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->next
, поскольку ->
имеет более высокий приоритет, чем *
, это эквивалентно *(head->next)
, Что вы хотите (*head)->next
так что вам нужны скобки.
Это связано с этим:
**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)