Search code examples
cprintfunsignedshortformat-specifiers

assign zero in unsigned short int in c


I try to assign zero to a field in a structure called list

list.ultimo = 0;

but when I use printf

printf("%d", list.ultimo);

I get the result

32766

but when I add

unsigned short int cero = 0;

the result of printf is correct, no matter that does not use cero. why?

lista.h

#ifndef LISTA_H
#define LISTA_H

typedef struct{
  elemento lista[TAMANOMAX];
  unsigned short int ultimo;
}LISTA;

void Insertar(elemento, unsigned short int posicion, LISTA);
#endif

lista.c

#include<stdio.h>

typedef short int elemento;
#ifndef TAMANOMAX
#define TAMANOMAX 10
#endif
#include"lista.h"

void Insertar(elemento x, unsigned short int p, LISTA lista){
  if (lista.ultimo >= TAMANOMAX){
    puts("full list");
    printf("%hu",lista.ultimo); 
  }
}

main.c

#include<stdio.h>

typedef unsigned short int elemento;
#define TAMANOMAX 4
#include"lista.h"

int main(){
  LISTA esferas;
  esferas.ultimo = 0; 
  Insertar(2,0,esferas);
  printf("\n%hu\n", esferas.ultimo);
  return 0; 
}

the result is

$gcc -Wall lista.c main.c

full list

32765

0

I'm new to this, I'm slow for now, I regret the delay


Solution

  • Use %hd to print a short int and %hu to print an unsigned short int. %d is for int.

    EDIT: Now that you have posted the full code, it appears that TAMANOMAX is set to 10 in lista.c, but set to 4 in main.c, leading to an incompatibilty between your main() function and the Insertar one. You should have the same value in all files. And if you want to work with different array lengths, add a length member in your LISTA structure. But TAMANOMAX should absolutely be the same everywhere, else you're in fact working with different data types and your program won't work.