Click here to Skip to main content
15,867,835 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
link->filename = filename;
   ^~~~


I have the following snippet:
//insert link at the first location
void insertFirst(int key, int data, int filename) {
   //create a link
   //struct node *link = (struct node*) malloc(sizeof(struct node));
	   
   struct node *link = malloc((sizeof *link) + 25 * (sizeof *link->filename));
   link->key = key;
   link->data = data;
   link->filename = filename;
   
   //point it to old first node
   link->next = head;
	
   //point first to new first node
   head = link;
}


What I have tried:

I've tried variations of the pointer, but clearly, not getting anywhere! Please help!

Thx,
Iris
Posted
Updated 24-Mar-22 5:04am
Comments
jeron1 24-Mar-22 11:02am    
It might help if you add the node struct definition to the original post.

Probably, it's the datatypes:
C
void insertFirst(int key, int data, int filename) {
...
   struct node *link = malloc((sizeof *link) + 25 * (sizeof *link->filename));
...
   link->filename = filename;
The value you pass in is a integer, but the malloc implies that link->filename is an array ...
 
Share this answer
 
Generally, one must cast the result of malloc to the type you want to use. Something like this :
C++
struct node *link = (struct node *) malloc((sizeof *link) + 25 * (sizeof *link->filename));
If you have declared node like this :
C++
struct node
{
};
then the preceding struct word is not needed in the cast and you can declare variables like this :
C++
node * link = NULL;
Incidentally, I always use calloc instead of malloc because it initializes the allocated memory to zeros automatically.
 
Share this answer
 
Comments
k5054 24-Mar-22 11:36am    
The OP has marked this question as C, not C++, so struct node is required. It is also the case that C does not require that assignments from void * be cast to the correct type, but it is still a good idea.
Iris Koren 24-Mar-22 12:01pm    
main.c: In function 'insertFirst':
main.c:45:4: error: invalid use of flexible array member
link->filename = filename;
^~~~
main.c: In function 'sort':
main.c:173:4: error: invalid use of flexible array member
current->filename = next->filename;
^~~~~~~
main.c:174:4: error: invalid use of flexible array member
next->filename = tempFilename;
^~~~
main.c: In function 'main':

Still getting these errors!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900