Cypert
Cypert

Reputation: 159

Changing the memory address instead of the value in a struct on C

This is my program. (Sorry, the constants and names of structs and variables are in my language)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>

/*CONSTANTES*/
#define MAX_CHAR 8
#define MAX_NOM_IMPR (20+1)
#define NUM_ELEM 10
#define MAX_IMPR 4
#define MAX_FICHEROS 6
#define ERROR_ARGC 0
#define ERROR_LONG 1
#define ERROR_COLALLENA 2
#define ERROR_NO_OPCION 3
#define ERROR_MAX_IMPR 4
#define ERROR_NOM_REP 5
#define ERROR_NO_IMP 6
#define ERROR_NO_IMP_REP 7
#define ERROR_LONG_IMPR 8

/*TIPOS DE DATOS*/
typedef char Telemento[MAX_CHAR+5];

typedef struct{
   Telemento arraycola[NUM_ELEM];
   int inicio;
   int final;
}TCola;

typedef char TNombreImpresora[MAX_NOM_IMPR];

typedef struct{
   TNombreImpresora nombreimpresora;
   int numerodeficherosencola;
   TCola colaImpresora;
}TImpresora;

typedef struct{
   TImpresora impresora;
   int ocupado;
}TCelda;

typedef TCelda Tlistaimpresora[MAX_IMPR];


int main(){
   Tlistaimpresora listaimpresora;

   listaimpresora[1].ocupado=1;
   printf("%s", listaimpresora[1].ocupado);
}

When I run it, it crashes and I figured out that: Instead of changing the value of ocupado, I changed the memory address and I don't know why. What am I doing wrong?

Upvotes: 0

Views: 283

Answers (2)

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4041

You are printing the integer variable in string format. So this is the reason for getting the segmentation fault. So make this into

printf("%d", listaimpresora[1].ocupado);

You will get the answer.

Upvotes: 2

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

You did not post the Tlistaimpresora structure details.

However, there are some common mistakes.

  1. you have defined a single variable of type Tlistaimpresora, and you're accessing listaimpresora[1] ?

  2. considered Tlistaimpresora is a typedef of struct abc *, you did not allocate memory for the variable.


EDIT:

well, after the full code, it looks your problem is here

printf("%s", listaimpresora[1].ocupado);

listaimpresora[1].ocupado is of type int and needs %d format specifier. %s specifier is used to print strings and expects a null-terminated string to print for.

Upvotes: 3

Related Questions