Why doesn't my C struct get any data in input? - c

So, I was trying to write this program in which it should be possible to create a dynamic list in which are stored data about some cars (model, colour, year) and then it should be possible to view a list of all of them. There are no errors in the program, and no segmentation fault, however as soon as I try to visualize the list, I get no output. I tried using GDB to debug it, and the struct pointer doesn't actually get any data during the input. Here is the whole code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node{
char modello[81];
char colore[81];
int anno;
struct node *next;
};
typedef struct node car;
car* insertNode(car* head);
car* destroyer(car* head);
void visualizer(car *head);
int main(){
car *head = NULL;
int n,tasto;
char option,enter;
do{
printf("Premere 1 per inserire un nuovo veicolo nel catalogo.\n");
printf("Premere 2 per visualizzare l'intero catalogo.\n");
printf("Premere qualsiasi altro tasto per uscire.\n\n");
scanf("%i",&tasto);
switch (tasto){
case 1:
insertNode(head);
break;
case 2:
visualizer(head);
break;
default:
break;
}
}while(tasto==1||tasto==2);
if(head!=NULL)
head=destroyer(head);
printf("Uscita.\n");
return 0;
}
car* insertNode(car *head){
car *temp;
car *prec;
temp=(car *)malloc(sizeof(car));
if(temp!=NULL){
temp->next=NULL;
if(head==NULL)
head=temp;
else{//Raggiungi il termine della lista
for(prec=head;(prec->next)!=NULL;prec=(prec->next));
prec->next=temp;
}
printf("Inserire il modello dell'auto: ");
scanf("%s",&temp->modello);
printf("Inserire il colore dell'auto: ");
scanf("%s",&temp->colore);
printf("Inserire l'anno di immatricolazione dell'auto: ");
scanf("%i",&temp->anno);
printf("\n");
}
else
printf("Memoria esaurita!\n");
return head;
}
void visualizer(car* head){
car *temp;
int i=1;
temp=head;
while(temp!=NULL){
printf("Auto numero %i:\n",i);
printf("Modello: %s.\n",temp->modello);
printf("Colore: %s.\n",temp->colore);
printf("Anno di immatricolazione: %i.\n",temp->anno);
printf("\n");
i++;
temp=temp->next;
}
}
car *destroyer(car* head){
car *temp;
while(head!=NULL){
temp=head;
head=head->next;
free(temp);
}
return NULL;
}
Can someone please explain why this happens? I have no clue about what's wrong with this.

The first error is in the do while, when you are at about line 31 in the case switch you don't store the return of the insert function anywhere. Here it is the fixed code:
do{
printf("Premere 1 per inserire un nuovo veicolo nel catalogo.\n");
printf("Premere 2 per visualizzare l'intero catalogo.\n");
printf("Premere qualsiasi altro tasto per uscire.\n\n");
scanf("%i",&tasto);
switch (tasto){
case 1:
head=insertNode(head);
break;
case 2:
visualizer(head);
break;
default:
break;
}
}while(tasto==1||tasto==2);
The second error is when you are getting the value from keyboard in insert node.
You are using the "&" operator when you already have the address of the array you want to fill, because you are indeed working with arrays. Here you can see the fixed code:
car* insertNode(car *head){
car *temp;
car *prec;
temp=(car *)malloc(sizeof(car));
if(temp!=NULL){
temp->next=NULL;
if(head==NULL)
head=temp;
else{//Raggiungi il termine della lista
for(prec=head;(prec->next)!=NULL;prec=(prec->next));
prec->next=temp;
}
printf("Inserire il modello dell'auto: ");
scanf("%s",temp->modello);
printf("Inserire il colore dell'auto: ");
scanf("%s",temp->colore);
printf("Inserire l'anno di immatricolazione dell'auto: ");
scanf("%i",&temp->anno);
printf("\n");
}
else
printf("Memoria esaurita!\n");
return head;
}

Related

insert one element among others in a list language C

Hi I'm trying to insert an element inside a list following a certain order(I have to add a equilateral triangle). When I try to use the code I can insert data(triangle measurements) but when I try to print list nothing appear :/.So I think that I wrote bad something in "inserisciPerPerimetro". Some word is written in italian and this is only a part of the code(two functions to add a triangle in my list),if u have to see also other parts let me know.
Thanks all!
This is my code:
typedef struct punto {
int x;
int y;
} PUNTO;
typedef struct triangolo {
PUNTO v;
int lato;
} TRIANGOLO;
typedef struct nodo {
TRIANGOLO t;
struct nodo *next;
} NODO;
int perimetro(TRIANGOLO t) {
return t.lato*3;
}
void stampaTriangolo(TRIANGOLO t) {
printf("Il triangolo ha il lato uguale a: %d con un perimetro pari a %d, il vertice in alto ha coordinate (%d,%d)\n",
t.lato, perimetro(t),t.v.x,t.v.y);
}
void stampaLista(NODO *head) {
if(head->next==NULL) {
printf("Lista vuota!\n");
} else {
while(head->next != NULL) {
head = head->next;
stampaTriangolo(head->t);
}
}
}
TRIANGOLO creaTriangolo() {
TRIANGOLO nuovo;
printf("Inserisci il lato del nuovo triangolo: ");
scanf("%d", &nuovo.lato);
printf("\n");
printf("Inserisci le coordinate del vertice con y maggiore:\n");
printf("x: ");
scanf("%d",&nuovo.v.x);
printf("\n");
printf("y: ");
scanf("%d",&nuovo.v.y);
printf("\n");
return nuovo;
}
void inserisciPerPerimetro(NODO *head) {
NODO* nuovoNodo;
nuovoNodo = malloc(sizeof(NODO));
nuovoNodo->t = creaTriangolo();
nuovoNodo->next = NULL;
if(head==NULL) {
head = nuovoNodo;
} else {
//Ordinamento per perimetro crescente
while(head->next != NULL)
if(perimetro(nuovoNodo->t) < perimetro(head->t)) {
nuovoNodo->next = head->next;
head->next = nuovoNodo;
} else {
head = head->next;
}
printf("Inserimento effettuato!\n");
}
}
int main() {
/* inizializza la lista */
NODO *head = malloc(sizeof(NODO));
head->next = NULL;
int risposta = -1; // per interazione con utente
while(risposta != 0) {
/* richiedi un'operazione all'utente */
printf("Che operazione vuoi svolgere?\n");
printf("1 -> Inserisci un triangolo nella lista ordinata secondo il perimetro crescente\n");
printf("2 -> Cancella il triangolo in testa alla lista\n");
printf("3 -> Visualizza la lista di triangoli\n");
printf("0 -> Termina il programma\n");
scanf("%d", &risposta);
/* gestisci le operazioni dell'utente */
if(risposta==1) {
inserisciPerPerimetro(head);
}
//else if(risposta==2)
//lista = cancellazione(lista);
else if(risposta==3) {
stampaLista(head);
}
else if(risposta==0) {
printf("Finito!\n\n");
}
else {
printf("Selezione non valida!\n\n");
}
}
}
I'm going to assume that you're holding a NODO* in some outer scope, and calling inserisciPerPerimetro on that pointer.
If you consider just the first time you do this (when the list is empty), your code will do head = nuovoNodo; so you will be putting the address of the newly allocated node into the pointer head. But this is a local copy of the parameter that you passed to the function, so the pointer in the outer scope will remain unchanged (and its value will be NULL). The next time you call the function, the list will still be empty.
One possible way to solve this is by passing a pointer to your head pointer to the function, so that the value of the pointer in the outer scope can be modified.
That is, the function should be defined like this:
void inserisciPerPerimetro(NODO **head)
Inside the function, modifications to head should be implemented as:
*head = nuovoNodo;
And in the outer scope you should have something like:
/*...*/
NODO* head = NULL;
inserisciPerPerimetro(&head);
/*...*/
EDIT:
Note that you are somewhat inconsistent with the node allocations: The head node is allocated in the outer scope (does it ever get its own triangle?), and all the others are allocated within the function. On the other hand, you check inside the function whether head is NULL - how can that happen if you allocate the list head in the outer scope?
Secondly, note that in the first call to inserisciPerPerimetro the while loop will be skipped because head->next is always NULL. This is because you don't handle the case where the new node needs to be inserted after the last node in the list.

queue list C program works but only shows 1 of the variables it's supposed to

so my program is suppose to receive 4 strings and one int input by the user and store them in a struct node and put them in a queue list and you have a menu that can delete the node at the front or check the info of each of them but for some reason only the Int variable is shown and the other variables that are stored in char[] don't show up. I tried putting the print function on diferent places and also try to use diferent ways to call the info but none help. heres some exceprts from the code and heres a link to it in full https://hastebin.com/isahijoyer.cpp
case 3:
val = peek(q);
if (val != -1)
printf("\nAs informações do Aviao no inicio da fila são:\n");
printf("ID: %s\t", q->front->id);
printf("Numero De Passageiros: %d\t", val);
printf("Destino: %s\t", q->front->des);
printf("Empressa: %s\t", q->front->comp);
printf("Modelo: %s\t", q->front->mod);
break;
case 4:
q = display(q);
break;
case 5:
printf("Quantidade de avioes esperando eh: %d\t", cont);
break;
}
struct queue *display(struct queue *q)
{
struct node *ptr;
ptr = q -> front;
if(ptr == NULL)
printf("\nA FILA ESTA VAZIA\n");
else
{
printf("\n");
while(ptr!=q -> rear)
{
printf("ID: %s\t", ptr -> id);
ptr = ptr -> next;
}
printf("ID: %s\t", ptr -> id);
return q;
}
}
struct queue *insert(struct queue *q,int val,char ide[10],char dest[10],char compa[10],char mode[10])
{
struct node *ptr;
ptr = (struct node*)malloc(sizeof(struct node));
ptr -> pass = val;
strcpy(ide, ptr->id);
strcpy(dest, ptr->des);
strcpy(compa, ptr->comp);
strcpy(mode, ptr->mod);
The first parameter to strcpy is the destination.

this c program runs without error but search,delete,update funtion is not working

#include<stdlib.h>
#include<string.h>
#include<stdio.h>
struct Node
{
char firstname[100];
char lastname[100];
char number[100];
char mail[100];
struct Node *next;
}*head;
void insert(char* firstname,char* lastname,char* number,char* mail)
{
struct Node * node=(struct Node *)malloc(sizeof(struct Node));
strcpy(node->firstname, firstname);
strcpy(node->lastname, lastname);
strcpy(node->number, number);
strcpy(node->mail, mail);
node->next=NULL;
if(head==NULL)
{
head=node;
}
else{
node->next=head;
head=node;
}
}
void search(char* firstname)
{
struct Node * temp = head;
while(temp!=NULL){
if(temp->firstname==firstname){
printf("Contact Found");
printf("Firstname:%s\n",temp->firstname);
printf("Lastname:%s\n",temp->lastname);
printf("PhoneNumber:%s\n",temp->number);
printf("Mail Id:%s\n",temp->mail);
return;
}
temp = temp->next;
}
printf("%s is not found in the contact \n",firstname);
}
void update(char* firstname)
{
struct Node * temp=head;
while(temp!=NULL){
if(temp->firstname==firstname){
printf("Contact Found");
printf("Enter the new Phone number for %s\n",temp->firstname);
scanf("%s",temp->number);
printf("Contact Updated Successfully\n");
return;
}
temp=temp->next;
}
printf("%s is not found in the contact \n",firstname);
}
void delete(char* firstname)
{
struct Node * temp1 = head;
struct Node * temp2 = head;
while(temp1!=NULL){
if(temp1->firstname==firstname){
printf("Contact Found for deleting\n");
if(temp1==temp2){
head = head->next;
free(temp1);
}
else{
temp2->next = temp1->next;
free(temp1);
}
printf("Contact deleted Successfully\n");
return;
}
temp2=temp1;
temp1=temp1->next;
}
printf("%s is not found in the contact \n",firstname);
}
void display()
{
struct Node * temp=head;
while(temp!=NULL){
printf("Firstname:%s\n",temp->firstname);
printf("Lastname:%s\n",temp->lastname);
printf("PhoneNumber:%s\n",temp->number);
printf("Mail Id:%s\n",temp->mail);
temp = temp->next;
}
}
int main()
{
head = NULL;
int choice;
char firstname[100];
char lastname[100];
char number[100];
char mail[100];
printf("-------Welcome--------\n ");
printf("1.Insert a Contact\n2.Search a Contact\n3.Delete a Contact\n4.Update a Contact\n5.Display all the Contacts");
do
{
printf("\nEnter Choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter Firstname:");
scanf("%s",firstname);
printf("Enter Lastname:");
scanf("%s",lastname);
printf("Enter PhoneNumber:");
scanf("%s",number);
printf("Enter Mail Id:");
scanf("%s",mail);
insert(firstname,lastname,number,mail);
break;
case 2:
printf("Enter Firstname to Search:");
scanf("%s",firstname);
search(firstname);
break;
case 3:
printf("Enter Firstname to Delete:");
scanf("%s",firstname);
delete(firstname);
break;
case 4:
printf("Enter Firstname to Update:");
scanf("%s",firstname);
update(firstname);
break;
case 5:
display();
break;
}
}while (choice != 0);
}
this c program runs without error but search,delete,update funtion is not working...you can refer the img for more details.
tommorrow i have to submit my mini project..so if anyone knows c program please help me
Enter Choice: 2
Enter Firstname to Search:durai
durai is not found in the contact
Enter Choice: 3
Enter Firstname to Delete:durai
durai is not found in the contact
Enter Choice: 4
Enter Firstname to Update:durai
durai is not found in the contact
these are the errors which i'm getting
For example within the function search you are trying to compare two pointers that point to different extents of memory
if(temp->firstname==firstname){
So the condition evaluates to false even if the pointed strings are equal each other. You have to use the standard string function strcmp
For example
if( strcmp( temp->firstname, firstname ) == 0 ){
Pay attention to that all function parameters that have the type char * should be declared as having the type const char *.
Also it is a bad idea when the functions depend on the global variable head. For example in this case you can not create more than one list in a program.

(Binary tree) Code doesn't work but returns no error when compiling

When compiling this code, the compiler doesn't return any warnings or errors but the code simply doesn't work.
The function inserirDado is supposed to recursively create nodes and store values on them, at node.valor, applying the conditions I set before.
void inserirDado(struct node **no, int numero)
{
if(*no == NULL) { //Se nao houver um nodo anterior, o primeiro numero se torna RAIZ.
* no = (struct node *) malloc(sizeof(struct node));
(*no)->direita = NULL;
(*no)->esquerda = NULL;
(*no)->valor = numero;
}else{ //Caso contrario, a definicao do numero, se entrara no nodo esquerdo ou direito.
if (numero < (*no)->valor) {
inserirDado(&(*no)->esquerda, numero);
}
else
{
inserirDado(&(*no)->direita, numero);
}
}
}
At emOrdem, the functions calls itself until it reaches the leaves, then it should print the values stored at node.valor :
void emOrdem(struct node *no)
{
if(no != NULL)
{
emOrdem(no->esquerda);
printf("%i", no->valor);
emOrdem(no->direita);
}
}
The complete code is:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int valor;
struct node *esquerda;
struct node *direita;
};
void inserirDado(struct node **no, int numero);
void emOrdem(struct node *no);
int main(void) {
struct node **arvore1;
inserirDado(arvore1, 4);
inserirDado(arvore1, 2);
inserirDado(arvore1, 3);
inserirDado(arvore1, 10);
emOrdem(*arvore1);
}
//Funcao de colocar um numero aleatoria dentro de um Node.
//Ao fazer isso com varios numeros, serao criados nodos com descendentes.
void inserirDado(struct node **no, int numero)
{
if(*no == NULL) { //Se nao houver um nodo anterior, o primeiro numero se torna RAIZ.
* no = (struct node *) malloc(sizeof(struct node));
(*no)->direita = NULL;
(*no)->esquerda = NULL;
(*no)->valor = numero;
}else{ //Caso contrario, a definicao do numero, se entrara no nodo esquerdo ou direito.
if (numero < (*no)->valor) {
inserirDado(&(*no)->esquerda, numero);
}
else
{
inserirDado(&(*no)->direita, numero);
}
}
}
void emOrdem(struct node *no)
{
if(no != NULL)
{
emOrdem(no->esquerda);
printf("%i", no->valor);
emOrdem(no->direita);
}
}
(1) Actually you should receive SEG Fault because you haven't initialized arovore1 to NULL.
(2) The important thing to mention here is, we use double pointers to get rid of return values. And what you have done here is a bit contradicting that.
--> Basically we'll create a node (arvore1) and then send the address of the node (&arvore1)
to the insertNode (inserirDado) function and inside that, we update corresponding node in that
address to the newly created node (temp).
I have attached the working code here. Please refer this and incase any doubts you can comment them down.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int valor;
struct node *esquerda;
struct node *direita;
};
void inserirDado(struct node **no, int numero);
void emOrdem(struct node *no);
int main(void) {
struct node *arvore1 = NULL;
inserirDado(&arvore1, 4);
emOrdem(arvore1);
}
//Funcao de colocar um numero aleatoria dentro de um Node.
//Ao fazer isso com varios numeros, serao criados nodos com descendentes.
void inserirDado(struct node **no, int numero)
{
if(*no == NULL) { //Se nao houver um nodo anterior, o primeiro numero se torna RAIZ.
struct node *temp = (struct node *) malloc(sizeof(struct node));
(temp)->direita = NULL;
(temp)->esquerda = NULL;
(temp)->valor = numero;
*no = temp;
}else{ //Caso contrario, a definicao do numero, se entrara no nodo esquerdo ou direito.
if (numero < (*no)->valor) {
inserirDado(&(*no)->esquerda, numero);
}
else
{
inserirDado(&(*no)->direita, numero);
}
}
}
void emOrdem(struct node *no)
{
if(no != NULL)
{
emOrdem(no->esquerda);
printf("%d", no->valor);
emOrdem(no->direita);
}
}
If you compile this code with GCC 10, with switches -W -Wextra -Wall (which isn't all warnings, by the way), you get:
<source>: In function 'main':
<source>:18:5: warning: 'arvore1' is used uninitialized in this function [-Wuninitialized]
18 | inserirDado(arvore1, 4);
| ^~~~~~~~~~~~~~~~~~~~~~~
GodBolt
and that shows you where the problem is: You're trying to initialize the place arvore1 is pointing to instead of initializing it.
Please also read:
Why should I always enable compiler warnings?
You must allocate buffer and assign it to arvore1 before passing that to inserirDado.
int main(void) {
struct node **arvore1 = malloc(sizeof(struct node*)); // add malloc()
inserirDado(arvore1, 4);
inserirDado(arvore1, 2);
inserirDado(arvore1, 3);
inserirDado(arvore1, 10);
emOrdem(*arvore1);
}
Another option is to change arvore1 from "a pointer to pointer" to "a pointer",
and pass pointer to that to inserirDado.
int main(void) {
struct node *arvore1 = NULL;
inserirDado(&arvore1, 4);
inserirDado(&arvore1, 2);
inserirDado(&arvore1, 3);
inserirDado(&arvore1, 10);
emOrdem(arvore1);
}

C function insert item in list

I have to create a list where each node contains the information of a game. Data are acquired by keyboard. So I have to create an insert function(inserisciTestaLista) in the list,but when I run the program stops. I have no compilation errors.
This's output:
...\Debug\progetto1.exe (processo 7356) terminato. Codice restituito: -1073741819.
Premere un tasto qualsiasi per chiudere questa finestra...
this's the code
#include <stdio.h>
#include <stdlib.h>
typedef struct s_partita {
char team1[32], team2[32];
int set1, set2;
char data[11];
}t_partita;
typedef struct nodo {
t_partita info;
struct nodo *next;
}t_nodo, *lista;
void inserisciTestaLista(lista *L, t_partita partita) {
lista aux;
aux = (lista)malloc(sizeof(t_nodo));
if (aux == NULL)
exit(1);
aux->info = partita;
aux->next = *L;
*L = aux;
}
int main() {
int scelta = 0;
lista L = NULL;
t_partita partita;
do {
printf("*****************MENU**************\n");
printf("0. ESCI\n");
printf("1. inserisci partita\n");
printf("2. stampa lista\n");
scanf("%d", &scelta);
switch (scelta) {
case 1: {
printf("Inserisci team 1: ");
scanf("%s", partita.team1);
printf("Inserisci team 2: ");
scanf("%s", partita.team2);
printf("Inserisci punteggio (esempio 3-1): ");
scanf("%d%d", &partita.set1, &partita.set2);
printf("Inserisci data (esempio 2020-01-01): ");
scanf("%s", partita.data);
inserisciTestaLista(L, partita);
break;
}
case 2: {
break;
}
}
} while (scelta != 0);
}
You can pass the memory address from the list in line 49.
inserisciTestaLista(&L, partita);

Resources