Error with sizeof | SoloLearn: Learn to code for FREE!


Error with sizeof

I created a code that asks you for coordinates and adds them to an array, to stop adding you have to input 1. after this the program prints every coordinate in the array but the sizeof() function isnt working, it keeps giving the same wrong dimension of the array regardless of the number of items in the array #include <stdio.h> #include <stdlib.h> struct punto{int x; int y;}; typedef struct punto punto; int main(){ punto *array=(punto*) malloc (5*sizeof(punto)); int i=0; int e=0; while(e!=1){ printf("inserisci la x\n"); scanf("%d",&(array[i].x)); printf("inserisci la y\n"); scanf("%d",&(array[i].y)); printf("PUNTO \n"); printf("%d %d \n", array[i].x, array[i].y); printf("se vuoi finire di inserire punti inserire 1 senno inserisci un qualsiasi altro numero\n"); scanf("%d",&e); i++; } printf("I punti nella lista sono %d \n",aa); i=0; while(i<(sizeof(array)/sizeof(punto))) { printf("%d %d\n",array[i].x,array[i].y); i++; } return 0; }

5/15/2020 6:46:25 PM

Guido Parlatore

1 Answer

New Answer


No matter how many puntos you enter the size of array nor the size of punto doesn't change. array is a pointer to a punto so that is the size in bytes you will get from sizeof(array). punto is a struct with 2 ints doesn't change either, so sizeof(punto) will always give the same result. Both of which have a size of 8 bytes here. 8/8 = 1