0

I'm trying to find out the length of an array but i get weird numbers…

#include <stdio.h>
#include <stdlib.h>

const int numOfCoordinates = 100;

typedef struct {
    int x;
    int y;
    int counter;
} Coordinate;

Coordinate *coordinatesMainArray;
Coordinate endPoint;
Coordinate startPoint;


int main(int argc, const char * argv[])
{
    endPoint.x = 8;
    endPoint.y = 3;
    endPoint.counter = 0;

    startPoint.x = 1;
    startPoint.y = 4;

    coordinatesMainArray = malloc(sizeof(Coordinate) * 1);
    coordinatesMainArray[0] = endPoint;



    int a = sizeof(coordinatesMainArray);
    int b = sizeof(coordinatesMainArray[0]);
    int coordinatesMainArrayLength = (a / b);

This is my code up until the part i need the length of coordinatesMainArray. But I get a = 8 and b = 12.

I assumed i would get two similar sizes so it shows i have one element in my array.

What am i doing wrong?

Nimrod Shai
  • 1,149
  • 13
  • 26
  • 2
    I assume that tutorial didn't have a chapter on the `sizeof` operator, did it... >. –  Jun 18 '13 at 11:59

4 Answers4

7

sizeof(coordinatesMainArray) gives you the size of the coordinatesMainArray variable - a Coordinate*

sizeof(coordinatesMainArray[0]) gives you the size of the first element in the coordinatesMainArray array - a Coordinate instance. sizeof(*coordinatesMainArray) would have been equivalent to this.

As an aside, there is no way to use a pointer to determine the size of an array. You'd need to store the array size separately and either pass this as well as the array pointer to other functions or guarantee that the array ends with a known terminator value (e.g. NULL)

simonc
  • 41,632
  • 12
  • 85
  • 103
1

In this case sizeof will only return the size of the coordinatesMainArray pointer (regardless of the size of its contents), because it is allocated on runtime.

Ry-
  • 218,210
  • 55
  • 464
  • 476
cutsoy
  • 10,127
  • 4
  • 40
  • 57
0

sizeof(coordinatesMainArray) gives you sizeof(Coordinate *) and sizeof(coordinatesMainArray[0]) gives you sizeof(Coordinate).

First is sizeof pointer and second is sizeof array element.

Dayal rai
  • 6,548
  • 22
  • 29
0

When you allocate a memory with malloc it doesn't maintain the size of the allocated chunk. At least not accessible to your regular code. If you allocate memory, you have to keep track of the size yourself.

In your example you just got the size of the pointer (a) and the size of a single structure (b).

Devolus
  • 21,661
  • 13
  • 66
  • 113