this is my first post here so if i make any mistake please tell me.
So i'm making this mini game for my class and i need to create a matrix of n size (from input) that is filled with a struct of enums, the function that does that is crea_scacchiera.
when i want to print the matrix i pass to another function (stampa_scacchiera), i tried everything but i cant find a solution to print the matrix without a segmentation fault.
the minigame is divided in 3 files : main.c that only prints a menu, gamelib.h that defines the enums and structts, and gamelib.c where there is the function that creates and print the matrix.
i think the matrix is filled right, i just cant find a way to print it in the other function.
//gamelib.h
extern void crea_mappa();
extern void gioca();
extern void termina_gioco();
enum Tipo_pericolo {nessun_pericolo, trappola, alieno} pericolo;
enum Stato_giocatore {vulnerabile, scudo_vita, solo_vita, solo_scudo};
enum Tipo_oggetto {nessun_oggetto, medikit, pozione, materiale, colpi_lanciarazzi} oggetto;
struct Giocatore
{
enum Stato_giocatore stato;
int Posizione_x;
int Posizione_y;
int zaino[4];
int alieni_uccisi;
};
struct Cella
{
enum Tipo_pericolo pericolo;
enum Tipo_oggetto oggetto;
};
//gamelib.c
#include "gamelib.h"
#include <stdio.h>
#include <stdlib.h>
//penso ci vadano anche dichiarazioni di variabili
int n;
void crea_scacchiera();
void stampa_scacchiera(struct Cella *scacchiera);
struct Cella *scacchiera= NULL;
static struct Giocatore Ninja;
static struct Giocatore Ciccio;
void crea_mappa()
{
int choice;
do {
printf(" \n");
printf("Sceglia cosa fare\n");
printf("1} crea scacchiera\n");
printf("2} stampa scacchiera\n");
printf("3} termina creazione\n");
printf(" \n");
scanf("%d",&choice );
switch (choice) {
case 1 :
crea_scacchiera();
break;
case 2 :
printf("stampa della scacchiera in corso\n");
stampa_scacchiera(scacchiera);
break;
case 3 :
printf("ritorno al menu della mappa\n");
system("clear");
break;
}
}
while (choice!=3);
}
void gioca()
{
printf("prova funzione, gioca\n");
}
void termina_gioco()
{
printf("prova funzione, termina gioco\n" );
}
void crea_scacchiera()
{
// enum Tipo_oggetto oggetto;
//enum Tipo_pericolo pericolo;
int i,j,rows,cols;
extern int n;
//static int perc1,perc2,perc3,perc4,perc5,perc6,perc7,perc8;
printf(" \n ");
printf("inserisci la grandezza della scacchiera\n ");
scanf("%d",&n);\
rows=n;
cols=n;
scacchiera = (struct Cella *)malloc(rows* cols* sizeof(struct Cella));
//int offset = i * cols + j;
for (i=0; i<n; i++){
for (j=0; j<n; j++){
scacchiera[i*cols+j].pericolo= trappola;
scacchiera[i*cols+j].oggetto= pozione;
}
}
Ninja.stato = solo_vita;
Ninja.Posizione_x= rand()%n+1;
Ninja.Posizione_y= rand()%n+1;
Ciccio.stato = solo_vita;
Ciccio.Posizione_x= rand()%n+1;
Ciccio.Posizione_y= rand()%n+1;
printf("%d\n",n );
}
void stampa_scacchiera(struct Cella *scacchiera) //FuncB
{
int i,j,cols;
cols = n;
extern int n;
cols=n;
for (i=0; i<n; i++){
for (j=0; j<n; j++){
printf("oggetto scacchiera [%d] [%d] : %d\n",i,j,(scacchiera[i*cols+j]).oggetto );
printf("pericolo scacchiera [%d] [%d] : %d\n",i,j,(scacchiera[i*cols+j]).pericolo );
}
}
}
I have modified the program now and this are the errors that is giving me
gamelib.c:154:39: error: declaration of ‘scacchiera’ shadows a global declaration [-Werror=shadow]
void stampa_scacchiera(struct Cella *scacchiera) //FuncB
^~~~~~~~~~
gamelib.c:11:15: note: shadowed declaration is here
struct Cella *scacchiera= NULL;
^~~~~~~~~~
Your program has majorly serious issues:
never use your original language in code. Always write in english (variable names, function names and so on). Otherwise almost noone will bother.
don't use shortcut names like crea_. How much time did it save you not to type those two missing letters? While everyone else will look at this and wonder what crea is. Yea, sure, "everyone" knows, its shortcut from create. But not everyone is you, not everyone is master of english and even then it will take them additional time of their live to decipher your "style" (read: mess).
formatting matters. Otherwise once again almost noone will bother.
Try this:
scacchiera = (struct Cella *)malloc(rows* cols* sizeof(struct Cella));
instead of
int *scacchiera = (int *)malloc(rows* cols* sizeof(struct Cella));
You forgot to initialize your global variable.
After trying to assign to global variable your compiler barks on you, because types don't match. Try this:
scacchiera = (struct Cella*)malloc(rows* cols* sizeof(struct Cella));
You also pass invalid value to printf (probably). Try this instead (removal of & operator). Otherwise you'll print address of a variable instead of it's value.
printf("oggetto scacchiera [%d] [%d] : %d\n",i,j,(scacchiera[i*cols+j]).oggetto );
printf("pericolo scacchiera [%d] [%d] : %d\n",i,j,(scacchiera[i*cols+j]).pericolo );
Related
I have a strange issue with my code :
I have a function generating a dynamic array of struct and only takes an int size as parameter.
It's work well until i try to add just a scanf("d";&size); to choose the size of my array, can't understand why i get a seg fault.
Note : There is no issue with compilation if i remove the line containing scanf
pokemon_t * createPkmDatabase( int taille){
printf("taille %d",taille);
pokemon_t *tableau=malloc(sizeof(pokemon_t)*taille);
...
...
}
int main(){
/*"taille" means size in french */
int taille=5;
printf("Saisir taille : ");
scanf("%d",&taille); /* <-- BREAKS EVERYTHING */
printf("valeur de taille : %d\n ",taille);
pokemon_t *database=createPkmDatabase(taille);
}
I don't get why changing the value of "taille" with a simple scanf change anything the value.
It doesn't even seems to enter in the function bc it doesn't even print the value of the size
There are no errors in the code shown.
Some remarks:
Use the correct type for sizes (size_t)
Always check the result of scanf and malloc
typedef struct {
int x,y,z;
}pokemon_t;
pokemon_t * createPkmDatabase(size_t taille){
printf("taille %d",taille);
pokemon_t *tableau=malloc(sizeof(*tableau)*taille);
return tableau;
}
int main(){
/*"taille" means size in french */
size_t taille;
printf("Saisir taille : ");
if(scanf("%zu",&taille) == 1)
{
printf("valeur de taille : %zu\n ",taille);
pokemon_t *database=createPkmDatabase(taille);
if(database)
{
printf("\nAllocation OK\n");
}
else
{
printf("\nAllocation FAILED\n");
}
free(database);
}
}
https://godbolt.org/z/ExjYe5G94
This code creates a binary search tree but it
runs sometimes normally and sometimes makes errors, even without changing anything in the code.
I can't get why this happening, what's the mistake ?
Even I changed the function that I used to create the tree from recursive to iterative but the same results.
#include <stdio.h>
#include <stdlib.h>
typedef struct sommet{
struct sommet * fg;
int val;
struct sommet * fd;
}sommet;
typedef sommet* ptrm;
ptrm creearbre(ptrm arbre,int ele);
void impression(ptrm arbre);
ptrm creearbre_rec(ptrm arbre,int ele);
int main()
{
ptrm arbre=NULL;
int tarbre,n;
printf("entre la taille de l'arbre:");
scanf("%d",&tarbre);
for(int i=0;i<tarbre;i++)
{
printf("entre l'element %d: ",i+1);
scanf("%d",&n);
arbre=creearbre_rec(arbre,n);
}
impression(arbre);
return 0;
}
ptrm creearbre_rec(ptrm arbre,int ele)
{
if(arbre==NULL)
{
arbre=malloc(sizeof arbre);
arbre->val=ele;
arbre->fd=NULL;
arbre->fg=NULL;
}
else if(arbre->val > ele)
arbre->fg=creearbre_rec(arbre->fg,ele);
else
arbre->fd=creearbre_rec(arbre->fd,ele);
return arbre;
}
void impression(ptrm arbre){
if(arbre != NULL){
printf(" %d -->", arbre->val);
impression(arbre->fg);
impression(arbre->fd);
}
}
ptrm creearbre(ptrm arbre,int ele){
ptrm p,q=arbre,r=NULL;
p=malloc(sizeof arbre);
p->val=ele;
p->fd=NULL;
p->fg=NULL;
if(arbre==NULL){
arbre=p;
}
else{
while(q!=NULL){
r=q;
if(ele > q->val)
q=q->fd;
else
q=q->fg;
}
if(ele > r->val)
r->fd=p;
else
r->fg=p;
}
return arbre;
}
The program has undefined behavior due to using an invalid size in the allocation of memory in statements
arbre=malloc(sizeof arbre);
and
p=malloc(sizeof arbre);
There are allocated memory for pointers instead of objects of the structure type.
You need to write
arbre=malloc(sizeof *arbre);
p=malloc(sizeof *arbre);
I cant figure out what I am doing wrong here / how do I fix it. It is giving me an indication of expecting an expression before struct on line 90. Can somebody help me out with this problem?
I want to print a structure that is in a function, but because of the 2 arguments behind it I cant find a proper way to code it. The other functions do work fine, but when I add this one it all goes wrong.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct geboorteDatum
{
int geboortedag;
int geboortemaand;
int geboortejaar;
};
struct Persoon
{
struct geboorteDatum;
char naam[20];
};
void printPersonen(struct Persoon *pt, int persoonCount);
void scanPersonen(int persoonCount);
int startMenu(void);
int main()
{
startMenu();
}
void printPersonen(struct Persoon *pt, int persoonCount)
{
printf("Gegevens persoon 1 : ");
printf("\n%s",pt[persoonCount].naam);
printf("\n%d",pt[persoonCount].geboortedag);
printf("\n%d",pt[persoonCount].geboortemaand);
printf("\n%d",pt[persoonCount].geboortejaar);
printf("\n");
}
void scanPersonen(int persoonCount)
{
struct Persoon pt[100];
printf("Voer Gegevens persoon . : \n");
scanf("%s", pt[persoonCount].naam);
scanf("%d", &pt[persoonCount].geboortedag);
scanf("%d", &pt[persoonCount].geboortemaand);
scanf("%d", &pt[persoonCount].geboortejaar);
}
int startMenu(void)
{
int keuze = 0;
int persoonCount = 0;
int * p1 = &persoonCount;
do
{
printf("MENU \n");
printf("1 : Voer een persoon in \n");
printf("2 : Toon alle geboortedatums \n");
printf("3 : Toon de jongste persoon \n");
printf("4 : Toon verjaardagen in een maand \n");
printf("0 : Einde \n\n");
printf("Maak een keus : ");
scanf("%d", &keuze);
printf("\n");
if(keuze == 1)
{
persoonCount++;
scanPersonen(persoonCount);
}
else if(keuze == 2)
{
printPersonen(struct Persoon *pt, int persoonCount);
}
else if(keuze == 3)
{
printf("jo3");
}
else if(keuze == 4)
{
printf("%d",persoonCount);
}
else
{
printf("Deze keus is niet mogelijk, kies opnieuw \n\n");
return startMenu();
}
} while (keuze > 0);
return persoonCount;
}
Well, in:
struct Persoon
{
struct geboorteDatum;
char naam[20];
};
that struct geboorteDatum specifies a type, but no member name! You can fix that by adding one struct geboorteDatum d;
Then in your print and scan functions replace
printf("\n%d",pt[persoonCount].geboortedag);
with
printf("\n%d",pt[persoonCount].d.geboortedag);
But even better would be to change the struct geboorteDatum to
struct Date {
int day;
int month;
int year;
}
as a birthday is just a date. you do not need a special type to represent birthdays.
Then struct Persoon becomes:
struct Person {
struct Data birthday;
char name[20];
};
And the print statements become
printf("\n%d", pt[persoonCount].birthday.day);
(And translate all code to English for easier sharing. I could understand the dutch part, but most people cannot.)
Cough
well....
printPersonen(struct Persoon *pt, int persoonCount);
means you are declaring a prototype, and in that context is incorrect. May be it should be:
printPersonen(pt, persoonCount);
I want to display structure members based on user input, but I don't know if I've stored the input properly.
When I try display all people, it just outputs random numbers.
These are the structures and function prototypes
#define MAX_NAME_LEN 15
#define MAX_NUM_PERSON 4
#define MAX_JOB_LENGTH 20
typedef struct birth_date
{
int month;
int day;
int year;
} person_birth_t;
typedef struct person
{
char pName[MAX_NAME_LEN];
char job[MAX_JOB_LENGTH];
person_birth_t birth_t;
} person_t[MAX_NUM_PERSON];
void print_menu (void);
void scanPerson(person_t p, int);
void displayPeople(person_t p);
This is the main code for the program, a menu is printed asking user to input a number, if a user enters 1 then it prompts them to add a person. Entering 2 displays all people entered.
int main(void)
{
/* TODO */
print_menu();
return 0;
}
void print_menu (void)
{
int choice;
person_t p;
static int index = 0;
int *indexP = NULL;
indexP = &index;
/*Print the menu*/
scanf("%d", &choice);
switch (choice)
{
case 1:
if (index < MAX_NUM_PERSON){
scanPerson(p, index);
++*indexP;
print_menu();
} else {
printf("Can't add more people - memory full \n");
print_menu();
}
break;
case 2:
displayPeople(p);
break;
case 3:
exit(0);
break;
default:
print_menu();
}
}
/*function called when add person is chosen from menu */
void scanFlight(person_t p, int index){
/*printf to enter name*/
scanf(" %s", p[index].pName);
/*printf to enter job*/
scanf("%s", p[index].job);
}
void displayPeople(person_t p){
for(int i = 0; i < MAX_NUM_PERSON; i++){
printf("%s %d-%d-%d %s \n",p[i].pName
,p[i].birth_t.month
,p[i].birth_t.day
,p[i].birth_t.year
,p[i].job);
}
}
I've tried other ways to take input and add it to a struct array, but I'm just not sure how to do it right.
person_t p;
Here, you use the local variable p (in print_menu function), so each recursion, you just print the parameters of the local variable that is not initialized.
To solve it, you can declare p as the global variable.
OT, in scanFlight function, to avoid overflow, you should change the scanf function to:
/*printf to enter name*/
scanf("%14s", p[index].pName);
/*printf to enter job*/
scanf("%20s", p[index].job);
And, rename scanPerson to scanFlight, because i do not see any implementation of scanPerson function in your code. I think it's typo, no ?
None of the methods were working, so instead of trying to figure it out, I scrapped the static index and indexP.
Instead, I initialized p with malloc:
person_t *p= malloc(MAX_NUM_PERSON * sizeof(person_t));
I changed the scan function to accommodate for the change and made index a pointer instead, and I made the display function pass the index.
When I ran it, the output was correct.
I've got this code, but it doesnt work, what's wrong?
I try to make massive of struct with dynamic size(C language)
after the second use of add_sala(); in main function Windows close programm.
Please help to solve this problem! Thanks!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
char trash[50];
int dyn_sala_id=1;
typedef struct
{
int id;
char number[6];
int persons;
char tech_inf[256];
} sala;
sala *sala_;
int add_sala()
{
int persons;
char number[6], tech_inf[256];
sala_ = (sala*)realloc(sala_,dyn_sala_id * sizeof(sala));
printf("Wpisz numer sali(max. 5 znakow): ");
fgets(number,6,stdin);
if(strlen(number)>5)
{
printf("Numer musi byc nie wiecej, niz 5 znakow!\n");
fflush(stdin);
add_sala();
return 0;
}
printf("Wpisz ilosc osob, ktora wmiesci sie w sale(max. 1000 osob): ");
scanf("%d", &persons);
if(persons==0 || persons>1000)
{
printf("Nie wolno wprowadzic litery oraz max. ilosc osob to 1000\n");
fflush(stdin);
add_sala();
return 0;
}
printf("Wpisz info o wyposazeniu sali(max. 255 znakow): ");
fgets(trash,50,stdin);
fgets(tech_inf,256,stdin);
if(strlen(tech_inf)>255)
{
printf("Info musi byc nie wiecej, niz 255 znakow!\n");
fflush(stdin);
add_sala();
return 0;
}
sala_[dyn_sala_id].id = dyn_sala_id;
strncpy(sala_[dyn_sala_id].number, number, 6);
sala_[dyn_sala_id].persons = persons;
strncpy(sala_[dyn_sala_id].tech_inf, tech_inf, 256);
printf("\nSala zostala dodana!\n\n");
printf("%d, %d, %s, %s",dyn_sala_id, persons, number, tech_inf);
dyn_sala_id+=1;
return 0;
}
int main()
{
add_sala();
printf("%s",sala_[1].number);
add_sala();
printf("'%s'",sala_[1].number);
printf("'%s'",sala_[2].number);
return 0;
}
Arrays in C are indexed from 0, so in main() the array indexing is off by 1.
add_sala();
printf("%s",sala_[1].number);
add_sala();
printf("'%s'",sala_[1].number);
printf("'%s'",sala_[2].number);
Also in the function add_sala() it is clear that the first time it is called you have the global
int dyn_sala_id=1;
which you use to allocate memory for one record with
sala_ = (sala*)realloc(sala_,dyn_sala_id * sizeof(sala));
but a bit further down, the indexing is again off by 1, where there is plainly only one array element
sala_[dyn_sala_id].id = dyn_sala_id;
Then, in that same function (although I can't read the error messages) it seems strange that after an apparent bad input, you recurse the function. Also, you have undefined behaviour with
fflush(stdin);
and I have not looked further, because the code will not work.