#include <stdio.h>
#include <stdlib.h>
typedef struct nodeWords
{
char * word;
int index;
struct nodeWords *left;
struct nodeWords *right;
} nodeWords;
int main(void)
{
nodeWords * node = malloc(sizeof(*node));
printf("%lu\n",sizeof(*node));
node->left = NULL;
node->right = NULL;
nodeWords * ihash = malloc(2 * sizeof(*ihash));
printf("%p \n", node->left);
//this part not working
ihash[0] = *node->left;
printf("%p\n",ihash[0]);
}
How can I assign node->left to ihash[0] and then be able to print out ihash[0], which should point to NULL?
There are two errors in your code and a few other 'minor issues' (I've commented these in the code posted below).
The first error is that you want to create an array of pointers to nodeWords, so you will need two stars in the declaration of ihash (one star will create an array of structure objects).
Second, in ihash[0] = *node->left;, you are dereferencing node twice (once with the preceding star operator, and once again with the -> operator.
The following code fixes these issues:
#include <stdio.h>
#include <stdlib.h>
typedef struct nodeWords {
char* word;
int index;
struct nodeWords* left;
struct nodeWords* right;
} nodeWords;
int main(void)
{
nodeWords* node = malloc(sizeof(*node));
printf("%zu\n", sizeof(*node)); // Should really use "%zu" for size_t
node->left = NULL;
node->right = NULL;
nodeWords** ihash = malloc(2 * sizeof(*ihash)); // You want an array of POINTERS so you need two ** in the type!
printf("%p \n", (void*)node->left); // Pedantic: %p expects a void*
//this part not working
ihash[0] = node->left; // The "*" preceding "node" was an error: the "->" inherentlt derefernces node
// ihash[0] = (*node).left; // An alternative way of dong the same thing
printf("%p\n", (void*)ihash[0]); // Pedantic: %p expects a void*
// Don't forget to free the allocated memory...
free(ihash);
free(node);
return 0; // Always good practice to put this EXPLICIT return statement in your "main"
}
Related
I am writing a code to create a linked list using structures in C language.
I have defined the structure with a data type and a pointer to structure type. Further I have used typedef to typecast this to Node_s.
I am using a function to initialise the first node; which basically won't contain any value but just returns the headpointer, which I will use to point to my next structure (node).
In the main block, I am initialising a structure pointer with Null value and then feeding the value from initialiser function to this pointer.
But this code is returning zsh: segmentation fault . Can someone explain me the issue!
#include <stdio.h>
#include <stdlib.h>
//Node* Initialize;
typedef struct Node {
int data;
struct Node* next;
} Node_s;
Node_s* Initialize(){
Node_s init_node;
Node_s* headlist;
init_node.data = 0;
init_node.next = headlist;
return headlist;
}
int main()
{
Node_s* ptr = NULL;
ptr = Initialize();
// 1st Node
ptr->data = 1;
Node_s* ptr2 = NULL;
ptr->next = ptr2;
// 2nd Node
ptr2->data = 1;
ptr2->next = NULL;
printf(" \n done deal %d", (*ptr2).data );
return 0;
}
main(): the variable ptr is uninitialized as returned from Initialize(). If it points to NULL or any other memory you don't have access to it will segfault when you deference it's members (ptr->data).
main(): the variable ptr2 is initialized to NULL, then you try to dereference it set its members. This will trigger a segfault if you get there.
Initialize(): init_node is a local variable and has no effect outside the function.
Initialize(): headlist is uninitialized as I mentioned above.
Initialize(): I suggest you change the signature to Node_s *Initialize(int data) so you can set the data to the value you need instead of a dummy value.
Here's a better starting point:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node_s;
Node_s *Initialize(int data) {
Node_s *headlist = malloc(sizeof(*headlist));
if(!headlist) {
printf("malloc failed\n");
return NULL;
}
headlist->data = data;
headlist->next = NULL;
printf("done deal %d\n", headlist->data);
return headlist;
}
int main() {
Node_s *ptr = Initialize(1);
if(!ptr)
return 1;
ptr->next = Initialize(2);
if(!ptr->next)
return 1
return 0;
}
The next step would be to eliminate the printf("done deal ...) statement in favor of a function that prints your linked list. Then write a function that frees the linked list. Then write a function that can Append(int data) an element to your list to replace Initialize().
I have a list defined as
typedef struct node {
Voo *voo;
ListaReservas nodeReservas; /* Ignore this */
struct node *next;
} *Node;
I created some functions to help me add or remove nodes from the list like:
/* creates a node */
Node criaNode(Voo v) {
Node new = (Node)malloc(sizeof(struct node));
new->voo = &v;
/* I had new->voo = v; but vscode told me it was wrong so i changed it to &v */
new->next = NULL;
return new;
}
Voo is defined as:
typedef struct {
int dia;
int mes;
int ano;
} Data;
typedef struct {
int horas;
int minutos;
} Tempo;
typedef struct {
char codigo[LEN_CODIGO + 1];
char partidaID[LEN_ID + 1];
char chegadaID[LEN_ID + 1];
Data datapartida;
Tempo horapartida;
Tempo duracao;
Data datachegada;
Tempo horachegada;
int capacidade;
} Voo;
Now I wanted to iterate through the list and print its values as such
Voo *v;
for (n = headVoos; n != NULL; n = n->next) {
v = n->voo;
printf("%s %s %s %.2d-%.2d-%d %.2d:%.2d\n",
v->codigo, v->partidaID, v->chegadaID,
v->datapartida.dia, v->datapartida.mes, v->datapartida.ano,
v->horapartida.horas, v->horapartida.minutos);
}
The program is not printing correctly. For example where it should appear
AA1 AAA AAD 16-03-2022 14:50
its appearing instead
� 146187376-32765--1940381952 40355300:50
What's causing this and how can I avoid it in the future?
EDIT
After replacing in the struct node the Voo *voo definition by Voo voo, I am now getting an error in one of the auxiliary functions:
/* deletes node */
Node eliminaNode(Node head, Voo v)
{
Node n, prev;
for (n = head, prev = NULL; n != NULL; prev = n, n = n->next)
{
if (n->voo == v) /* expression must have arithmetic or pointer error */
{
if (n == head)
head = n->next;
else
prev->next = n->next;
free(n->next);
free(n);
break;
}
}
return head;
}
In criaNode you're taking the address of the parameter v and returning it from the function via a pointer to dynamic memory. That address is no longer valid after the function returns. Subsequently dereferencing that invalid address then triggers undefined behavior.
It probably makes more sense for struct node to contain a Voo directly instead of a pointer to one. So change the member to a non-pointer:
Voo voo;
And assign the parameter directly:
new->voo = v;
There are multiple problems here:
there seems to be a confusion between structures and pointers to structures. In C, you must understand the difference between manipulating objects (allocating as local objects or from the head, passing as arguments or returning as values) and pointers to objects, which are a more idiomatic as arguments to functions and allow functions to modify the object they point to.
the confusion is amplified by a very error prone construction: hiding pointers behind typedefs. Do not do that, define object types for the actual structure, using the same or a different name as the struct tag, and make all pointers explicit with the * syntax.
you pass an actual Voo object as an argument and allocate a list node using the address of this argument. This is incorrect because the argument will be discarded as soon as the function returns, makeing the list point to invalid memory and explaining the weird output you observe.
Node eliminaNode(Node head, Voo v) should take a pointer to the head node and return a success indicator. It should take a Voo * argument and it should not free(n->next) because the next node is still in use after the removal.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#define LEN_CODIGO 30
#define LEN_ID 30
typedef struct Data {
int dia;
int mes;
int ano;
} Data;
typedef struct Tempo {
int horas;
int minutos;
} Tempo;
typedef struct Voo {
char codigo[LEN_CODIGO+ 1];
char partidaID[LEN_ID + 1];
char chegadaID[LEN_ID + 1];
Data datapartida;
Tempo horapartida;
Tempo duracao;
Data datachegada;
Tempo horachegada;
int capacidade;
} Voo;
typedef struct Node {
struct Voo *voo;
//ListaReservas nodeReservas; /* Ignore this */
struct Node *next;
} Node;
/* creates a node */
Node *criaNode(Voo *v) {
/* allocation with calloc is safer as the object will be initialized to 0 */
Node *nodep = calloc(1, sizeof(*new));
if (nodep) {
nodep->voo = v;
nodep->next = NULL;
}
return nodep;
}
/* deletes node */
int eliminaNode(Node **head, Voo *v) {
for (Node *n = *head, *prev = NULL; n != NULL; prev = n, n = n->next) {
if (n->voo == v) {
if (n == *head)
*head = n->next;
else
prev->next = n->next;
free(n);
return 1; /* article was found and freed */
}
}
return 0; /* article was not found */
}
void printList(const Node *head) {
for (const Node *n = head; n != NULL; n = n->next) {
const Voo *v = n->voo;
printf("%s %s %s %.2d-%.2d-%.2d %.2d:%.2d\n",
v->codigo, v->partidaID, v->chegadaID,
v->datapartida.dia, v->datapartida.mes, v->datapartida.ano,
v->horapartida.horas, v->horapartida.minutos);
}
}
I am trying to build a linked list from a string of integers separated by spaces. Each integer in the string will be added to the linked list except for -1. However, when I try to print the data in the head node of the list, I get the error Member reference base type 'Node *' (aka 'struct node *') is not a structure or union. Why can't I print head_ptr's data in that line?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node Node;
struct node {
int data;
Node *next;
};
void build_linked_list(Node **head_ptr) {
char *string = malloc(1028);
char *p = string, *found = string;
Node *nextNode = NULL;
if (fgets(string, 1028, stdin) != NULL) {
while ((found = strsep(&p, " \n")) != NULL) {
if (strcmp(found, "-1") == 1) {
Node node = {atoi(found), nextNode};
nextNode = &node;
}
}
}
*head_ptr = nextNode;
printf("%i\n", *head_ptr->data); // can't print data in head node
free(string);
}
int main() {
Node *head = NULL;
build_linked_list(&head);
return EXIT_SUCCESS;
}
you need to put parentheses around the head_ptr to make it work, like this: (*head_ptr)->data)
the problem arises since the compiler evaluates the expression as a dereference of a double pointer with a member of int, so first it tries to get the int member from the double pointer, which doesn't exist.
so that's why you need to put the parenthesis, so it will evaluate the head_ptr as a dereference of the double pointer, and will use the int member of that struct.
Why aren't the struct pointers initialized to NULL using the following code
code
#include <stdio.h>
#include <stdlib.h>
struct list_el
{
int val;
struct list_el * right, * left, *parent;
}item_default={0,NULL,NULL,NULL}; //Default values
typedef struct list_el node;
int main(int argc, char const *argv[])
{
node * new_node = (node*) malloc (sizeof(node));
(new_node == NULL) ? printf("0\n") : printf("1\n");
(new_node->parent == NULL) ? printf("0\n") : printf("1\n");
(new_node->right == NULL) ? printf("0\n") : printf("1\n");
(new_node->left == NULL) ? printf("0\n") : printf("1\n");
(new_node->val == 0) ? printf("0\n") : printf("1\n");
return 0;
}
Output
1
1
1
1
0
Is it some issue regarding the pointer initialisation syntax?
struct list_el
{
int val;
struct list_el * right, * left, *parent;
}item_default={0,NULL,NULL,NULL}; //Default values
This does not do what you think it does. You've basically written...
typename typedefinition variable = initial_value;
You've declared the type struct list_el, defined it as { int val; struct list_el * right, * left, *parent; }, declared a new variable of that type called item_default, and assigned it the value {0,NULL,NULL,NULL}.
Aside from the type definition, this is basically int foo = 0.
We can test that by printing out the parts of item_default.
int main(int argc, char const *argv[])
{
printf("%d\n", item_default.val);
printf("%p\n", item_default.right);
printf("%p\n", item_default.left);
printf("%p\n", item_default.parent);
return 0;
}
And these will be 0, 0x0 (ie. NULL), 0x0, 0x0.
Unfortunately, C has no defaults for types. You always must initialize them. When working with structs, this typically means writing new and destroy functions so initialization and cleanup happens consistently.
// Declare the type and typedef in one go.
// I've changed the name from node to Node_t to avoid clashing
// with variable names.
typedef struct node
{
int val;
struct node *right, *left, *parent;
} Node_t;
// Any functions for working with the struct should be prefixed
// with the struct's name for clarity.
Node_t *Node_new() {
Node_t *node = malloc(sizeof(Node_t));
node->val = 0;
node->right = NULL;
node->left = NULL;
node->parent = NULL;
return node;
}
int main() {
Node_t *node = Node_new();
printf("%d\n", node->val);
printf("%p\n", node->right);
// and so on
return 0;
}
Note that I did not use calloc. calloc fills the memory with zeros, but the machine's representation of a null pointer is not necessarily zero. Using NULL and 0 are safe, the compiler can do the translation from context, but calloc doesn't know what you're going to do with the memory its zeroing. It's a relatively minor portability concern that's probably more of a problem these days for embedded systems.
Structure is a data type, you don't give default values to data types. What you're doing is like give an int the default of 3. What you want is give an instance of your struct a default value, but that is not possible in C.
You could have a function to help you with that:
void init_struct(node* nd) {
if (nd != NULL) {
nd->val = 0;
nd->parent = nd->right = nd->left = NULL;
}
}
i dont know why the list returned is NULL, this is the code:
In my List.h
struct nodo_ {
char* dato;
struct nodo_ *next;
};
struct nodo_ *Lista;
/*Def list */
void createList(struct nodo_ **Lista);
in my main.c
struct nodo_ *Lista;
int main(){
createList(Lista);
while(Lista != NULL){
printf("The date is %s\n ",Lista->dato); //Error here now
Lisa = Lista->next;
}
return 0 ;
}
in my List.c im create the List :
void createList(struct nodo_ *Lista){
struct nodo_ *Aux_List = list_D;
aux_List = malloc(sizeof(struct nodo_));
char* path_a = "Hello";
char* path_B = "Minasan";
/* Store */
aux_List->dato = path_a;
aux_List = Aux_List->next;
aux_List = malloc(sizeof(struct nodo_));
aux_List->dato = path_b;
aux_List->next = NULL;
}
Thanks.
That pointer is being passed by value, i.e., a copy is made. If you wish to initialize the pointer to a completely new value then you must use another level of indirection (i.e., a nodo_**).
On a side note, typedefing pointer types is almost always a bad idea unless the type is truly opaque (which yours is not). One reason for this "rule" is evident when you consider another bug in your code:
auxList = (Lista*)malloc(sizeof(Lista));
You're allocating space for a pointer to noda_, not enough for a noda_ object. Also, don't cast the return value of malloc in C. It is redundant as a void* is safely and implicitly converted to any other pointer type and, if you forget to include stdlib.h, malloc will be assumed to be a function which returns int, and the cast hides the error. (only applies to compilers which implement C89 or an older version)
EDIT:
To initialize a pointer argument within a function:
void init(struct node **n) {
if(n)
*n = malloc(sizeof(struct node));
}
int main() {
struct node *n;
init(&n);
}
Short answer to your actual question before I dig into the code:
... why the list returned is NULL ...
There is no returned list, you neither use return to pass a result, nor set the value of an out parameter.
In your edited code:
void createList(struct nodo_ **Lista){
struct nodo_ *Aux_List = list_D;
aux_List = malloc(sizeof(struct nodo_));
you first set Aux_List to the current value of Lista, which you know isn't initialized yet, because you're trying to initialize it. Then you discard that value, overwriting aux_List with a new address returned by malloc. You never store anything into *Lista, which would be the only way for this function to work as declared.
As Ed suggests, your typedef is hiding lots of useful information from you, so let's expand it out
struct nodo {
char* dato;
struct nodo *next;
};
/*Def list */
void createList(struct nodo* list_D);
Now, you can see this createList is wrong: you can pass in the head node of a list (which is no use to it anyway), but there is no way for it to return a newly-allocated list to the caller.
Frankly your createList isn't a useful primitive anyway, so I'm going to start with a sensible foundation first:
struct nodo *alloc_nodo(char *dato, struct nodo *next)
{
struct nodo *n = malloc(sizeof(*n));
n->dato = dato;
n->next = next;
return n;
}
Now, before we re-write your createList using this, let's see what it does now:
void createList(struct nodo *list_D)
{
struct nodo *aux_List = list_D;
aux_List = malloc(sizeof(struct nodo_));
/* ^ so, we take the input argument and immediately discard it */
char* path_a = "Hello";
char* path_B = "Minasan";
/* Store */
aux_List->dato = path_a;
aux_List = Aux_List->next;
/* ^ note that we haven't initialized aux_List->next yet,
so this is a random pointer value */
aux_List = malloc(sizeof(struct nodo_));
/* again, we set aux_List to something,
but immediately overwrite and discard it */
aux_List->dato = path_b;
aux_List->next = NULL;
}
So, it ignores its input, returns no output, and leaks two partially-initialized nodes which aren't connected to each other. I believe you wanted to achieve something more like this:
struct nodo* create_my_list()
{
struct nodo *tail = alloc_nodo("Minasan", NULL);
/* the end (tail) of the linked list has a NULL next pointer */
struct nodo *head = alloc_nodo("Hello", tail);
/* the head of the linked list points to the next node */
return head;
/* like a snake, you hold a singly-linked list by the head */
}
If we write main to use this function now, it looks like:
int main()
{
struct nodo *head = create_my_list();
struct nodo *n;
for (n = head; n != NULL; n = n->next)
{
printf("The date is %s\n ", n->dato);
}
}