Error "initializer element is not constant" when allocate the memory - c

1 #include<stdio.h>
2 #include<malloc.h>
3
4 typedef struct node_t{
5 int i;
6 struct node_t* link;
7 }node;
8
9 node* head = (node *)malloc(sizeof(node));
10
11 if(head == NULL){
12 printf("\n malloc for head node failed! \n");
13 }
14
15 int main(){
16 int i = 10;
17 node* temp = NULL;
18 temp = (node *)malloc(sizeof(node));
19 if(temp == NULL){
20 printf("\n malloc for temp node failed! \n");
21 }
22 else{
23 while(i<=10){
24 ;
25 }
26 }
27 return 0;
28 }
compilation error:
linked.c:9:1: error: initializer element is not constant
linked.c:11:1: error: expected identifier or ‘(’ before ‘if’
I'm trying a simple linked list programme. It's not fully completed. I'm getting a compilation error. Couldn't understand why this happened.

Since you're defining head as a global, its initializer needs to be a constant--basically, the compiler/linker should be able to allocate space for it in the executable, write the initializer into the space, and be done. There's no provision for calling malloc as you've done above during initialization--you'll need to do that inside of main (or something you call from main).
#include <stdlib.h>
void init() {
head = malloc(sizeof(node));
}
int main() {
init();
// ...
}
In this case, the code you have in main never actually uses head though, so you may be able to skip all of the above without a problem.

9 node* head = (node *)malloc(sizeof(node));
10
11 if(head == NULL){
12 printf("\n malloc for head node failed! \n");
13 }
These lines are not possible outside the main() because any function call or executable should be inside the main() function or any function called from main.
For linked.c:9:1: error: initializer element is not constant
Only function definitions or any global initialization is possible outside main() but initializer must be constant expression`.
You can declare the head as global but initialization is wrong.
Do it like this :
node * head =NULL // here initialization using constant expression
void function () // any function
{
head = malloc(sizeof(node));
}
For linked.c:11:1: error: expected identifier,
if statement cannot be outside any function.
In your case , put these lines inside main and problem solved

head is a global varibale. Global and static varibales must be initialized by constant expressions, i.e. literals. so you can't do
node* head = (node *)malloc(sizeof(node));

You can't use malloc() in global scope.
or
you can do like follow
#include<stdio.h>
#include<malloc.h>
:
node* head
:
:
int main(){
:
:
head = (node *)malloc(sizeof(node));
:
:
}

Related

How can I use pointer in structures?

When I learn data structures in C, I got an error but I couldn't solve. How can I solve this problem?
#include <stdio.h>
#include <stdlib.h>
struct n {
int x;
n * next;
};
typedef n node;
int main() {
node * root;
root = (node * ) malloc (sizeof(node));
root -> x=10;
root -> next = (node * ) malloc (sizeof(node));
root -> next -> x=20;
root -> next -> next = (node * ) malloc(sizeof(node));
root -> next -> next -> x=30;
iter = root;
printf("%d",iter->x);
iter = iter -> next;
printf("%d",iter->x);
return 0;
}
5 5 D:\Dev C\Projects\main.c [Error] unknown type name 'n'
12 7 D:\Dev C\Projects\main.c [Error] request for member 'x' in something not a structure or union
13 7 D:\Dev C\Projects\main.c [Error] request for member 'next' in something not a structure or union
17 2 D:\Dev C\Projects\main.c [Error] 'iter' undeclared (first use in this function)
In your code a type named n does not exist.
That is why you have the line typedef n node; to make a type.
In C, the type of your structure is struct n not n.
So you need
typedef struct n node; to make a new type named node.
Within your struct, neither n nor node exist yet.
So there you need to do
struct n * next;
The last of your errors (though not explicitly covered by your question) then can be fixed by defining iter first.
node * root;
node * iter;

C - Memory leak on adding elements to odd numbered indices in array of linked lists, but not even

I have a simple linked list struct called node, an array of head nodes, a linkedListManage function, and an addNode function, however I would appreciate some help diagnosing a segfault issue that I do not understand.
I have traced the issue when adding nodes to a statement in main:
while(1) linkedListManage(*heads);
While the pointer to heads is included, I get a segfault whenever I am adding the second element (never the first) to any linked list head that is stored at the ODD INDEX (never any issues with the even index) in my array of linked list heads. I have tested this with an array size of 20 for the head and the problem still persisted to only affect the odd indices.
However, when I remove the pointer to heads:
while(1) linkedListManage(heads);
this removes the segfault error and allows my lists to add properly, but then gives the 2 warnings:
main.c:42:27: warning: incompatible pointer types passing 'node *[2]' to parameter of type
'node *' (aka 'struct node_t *') [-Wincompatible-pointer-types]
while(1) linkedListManage(heads);
^~~~~
main.c:27:27: note: passing argument to parameter 'heads' here
void linkedListManage(node* heads){
Below is my program, I would really like to know what is causing this issue so that I can learn more about whatever pointer issue this happens to be, and so i can stop having warnings. I am completely stumped as to why this issue would only appear on the odd indices.
#include <stdio.h>
#include <stdlib.h>
typedef struct node_t{
int data;
struct node_t* next;
} node;
void addNode(node* a){
int userInput;
node* current = a;
printf("Enter value: ");
scanf("%d", &userInput);
if (!current->data) current->data = userInput;
else {
while(current->next) current = current->next;
node* newNode = (node*)malloc(sizeof(node));
newNode->data = userInput;
current->next = newNode;
}
}
void linkedListManage(node* heads){
int userInput;
printf("Enter ID of list:\n");
scanf("%d", &userInput);
addNode(&heads[userInput]);
}
int main(){
node* heads[2];
heads[0] = (node*)malloc(sizeof(node));
heads[1] = (node*)malloc(sizeof(node));
while(1) linkedListManage(heads);
return 0;
}
while(1) linkedListManage(heads);
should be
while(1) linkedListManage(heads[1]);
as otherwise you are passing node ** to a function that expects node *.

Why is this linked list printing the last element indefinitely?

I was completing a Hackerrank challenge involving addition of elements to a linked list and printing it.
The input is of this format: A set of integers, in which the first element gives the size and the rest are the components of the list.
I completed the challenge in Java, but I am not able to do it in C.
Input of 4 2 3 4 1 should print 2 3 4 1, but this snippet that I coded is giving me 1 1 1 1 1 1 .... {truncated}
My approach: Declare a new struct temp of type Node (with the data input as data field, and NULL in next field), then iterate thorough the linked list with head as the starting point, and when it reaches the last element, change the next field of the last element to the address of the current element.
Code:
#include <stdlib.h>
#include <stdio.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
Node* insert(Node *head,int data)
{
Node temp = {data, NULL} ;
if (head == NULL)
{ head =&temp;
return head;
}
else{
Node* current = head ;
while(current->next !=NULL)
current = current->next ;
current->next = &temp;
return head;
}
}
void display(Node *head)
{
Node *start=head;
while(start)
{
printf("%d ",start->data);
start=start->next;
}
}
int main()
{
int T,data;
scanf("%d",&T);
Node *head=NULL;
while(T-->0){
scanf("%d",&data);
head=insert(head,data);
}
display(head);
}
List nodes must be allocated dynamically. This
Node temp = {data, NULL} ;
declares a local variable. Referring to its address outside the scope of its declaring function is undefined behavior.
Replace with
Node *temp = malloc(sizeof(Node));
temp->data = data;
temp->next = NULL;
Now thtat temp is a pointer, expression &temp has to be replaced with temp as well.
Because you save a pointer to a local variable in the list. When the insert function returns, the local variable temp will go out of scope and cease to exist. Saving a pointer to it and using that pointer will lead to undefined behavior. Find a good beginners book and read about dynamic allocation of memory.

segmentation fault when trying to deference pointer : C

I was trying to implement circular queue functionality. I am a C++ coder and I found it surprising that in C, struct cannot have member functions. Anyway this is my implementation:-
#include <stdio.h>
#include <stdlib.h>
struct node
{
int nvalue;
struct node *next;
};
struct CLlist
{
struct node* head;
struct node* tail;
int size;
};
void insert(struct CLlist *l,int num)
{
struct node *n=malloc(sizeof(struct node));
n->nvalue=num;
n->next=NULL;
if((l->head==l->tail)==NULL)
{
l->head=l->tail=n;
}
else if(l->head==l->tail && l->head!=NULL)
{
l->head->next=n;
l->tail=n;
l->tail->next=l->head;
}
else
{
l->tail->next=n;
l->tail=n;
l->tail->next=l->head;
}
l->size++;
}
void print(struct CLlist *l)
{
int idno=1;
printf("printing the linked list with size as %d\n",l->size);
struct node *cptr;
for(cptr=(l->head);cptr!=(l->tail);cptr=cptr->next)
{
printf("The idno is %d and the number is %d\n",idno,cptr->nvalue);
idno++;
}
//this is to print the last node in circular list : the tail node
idno++;
cptr=cptr->next;
printf("The idno is %d and the number is %d\n",idno,cptr->nvalue);
}
int main()
{
struct CLlist a;
struct CLlist *l;
l=&a;
insert(l,2);
insert(l,5);
insert(l,7);
insert(l,10);
insert(l,12);
print(l);
return 0;
}
I get segmentation fault in the line
printf("The idno is %d and the number is %d\n",idno,cptr->nvalue);
why does the error occur? I guess I am not passing l by pointer by value (passing pointers as by value) properly. could somebody help me in pointing out where I am going wrong?
Thanks
You never initialize the variable a in the main function, so its contents is indeterminate and using the members of that structure will lead to undefined behavior.
Your code has two issues, the first one more serious.
Your first issue is that the head and tail members of your CLlist structure are not being initialized to NULL, which can (non-deterministically) keep any real data from being stored in your structure. This can be fixed by adding the following 2 lines in main just before the first insert call:
l->head = NULL;
l->tail = NULL;
Your second problem is in this line:
if((l->head==l->tail)==NULL)
While it looks like this is comparing both l->head and l->tail to NULL, it's actually comparing l->head to l->tail, and then comparing that boolean result to NULL, which is effectively 0. The line should be changed to:
if((l->head == NULL) && (l->tail == NULL))
This will individually test both the head and tail pointers, and will only take that branch if they are both NULL.
You have a pointer
struct node *cptr;
// You're probably trying to access an unassigned pointer head in the next step
for(cptr=(l->head);cptr!=(l->tail);cptr=cptr->next)
As per the standards, there is no requirement that
a->head & a->tail are initialized to NULL
when you did
struct CLlist a;
Standard ISO/IEC 9899:201x clause 6.7.9->10 states
If an object that has automatic storage duration is not initialized
explicitly, its value is indeterminate.
In fact you're:
struct CLlist a;
// missing something here.
struct CLlist *l;
l=&a;

passing an uninitialized variable throwing an error using C

I have this code :
typedef struct node
{
int data;
struct node *left;
struct node *right;
} node;
void Build (node *root , int i)
{
if (i < 7)
{
root = (node *)malloc (sizeof(node));
root->data = i;
Build(root->left,2*i+1);
Build(root->right,2*i+2);
}
else
root = NULL;
}
void Print (node *root)
{
if (root)
{
printf ("%d ",root->data);
Print(root->left);
Print(root->right);
}
}
void main()
{
node *tree;
Build(tree,0);
Print(tree);
}
two things that I dont understand ,
1. why can't I pass Build(tree,0) ? it says it's uninitialized , but why shuold I care if it's uninitialized ? I'm allocating all the memory needed straight away so it's gonna be pointing on the new allocated node.
how can I fix this code? thank you!!!
Your node * to tree is uninitialized.
node *tree;
That matters because the code line
root = (node *)malloc (sizeof(node));
allocates memory to a local copy of root. Once you leave function scope of Build, the copy of root goes out of scope. Memory leak.
Remember, everything is passed by value in C.
If you really want Build to allocate the memory, the signature would have to be
void Build (node **root , int i)
and your code in that method would have to refer to *root instead of root.
Parameters are passed by value - the location in memory is not actually passed. So when you call Build, you're just passing in the value of tree, which happens to be uninitialized. The Build function creates a local root variable with that value - when you set root = ... in Build, you're over-writing that undefined value with the new value, but that new value is still just in the local root variable - it is never seen by the tree variable in main.
What you really want to do is have Build return the newly created tree pointer:
node * Build(int i)
{
node *root;
...
root->left = Build(2*i+1)
...
return root;
}
void main()
{
...
tree = Build(0);
...
}

Resources