-2

I use a macro to get the number of the elements of an integer array, and I could get the right result of the number of the integer array in the main function, but I got the wrong answer if I use a getData function and send the pointer of the integer array as a parameter. I want to know why I got this wrong answer. Thank you!

the code of my program as follow:

#include <stdio.h>

#define LENGTHOFINTARRAY(intArray) ((int)(sizeof(intArray)/sizeof(int)))

int main (int argc, char *argv[])
{
    int a[] = {5,8,9,4,11,7,15,25,1};

    int getData(int *data);
    printf("%d\n", LENGTHOFINTARRAY(a));
    getData(a);

    return 0;
}

int getData(int *data)
{
    int i = 0;
    for(i; i < LENGTHOFINTARRAY(data); i++)
    {
        printf("%d, %d\n", LENGTHOFINTARRAY(data), data[i]);
    }

    return 1;
}

and the result of my program is:

9

1, 5

I use gcc as my compiler.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Triangle23
  • 23
  • 5

3 Answers3

0

The type of int* data is just int* and not int[9] like in main. The size of int* is is the size of any other pointer (4 or 8 bytes usually). There is no way to get the size of an array from the pointer. And since arrays can't be passed by value in C (unless inside a struct or something) you have to pass the length of the array.

Tomer Arazy
  • 1,833
  • 10
  • 15
  • So, if I want to get the number of the integer array in my getData fuction, I must send the sent the number of the integer array as a parameter? Could I have another way the get this? – Triangle23 Apr 23 '13 at 10:34
  • Yes, you must send the size as a parameter and no, there is no other way. – Yexo Apr 23 '13 at 10:37
  • No, there's no way to tell how big an array is if you only have a pointer to its first element. – Timothy Jones Apr 23 '13 at 10:38
  • @liuzeli You can avoid passing the array size as a separate parameter if you set the final value of the array to a sentinel value that will never otherwise appear in the array. Other functions can then iterate through the array, stopping when they find the element with the sentinel value. – simonc Apr 23 '13 at 10:39
0

getData() sees data as an int*. It does not know how long it is.

You cannot determine the size of an array that is passed as a pointer to a function.

Elmar Peise
  • 14,014
  • 3
  • 21
  • 40
0

As you have defined

int a[] = {5,8,9,4,11,7,15,25,1};

    int getData(int *data);
    printf("%d\n", LENGTHOFINTARRAY(a));
    getData(a);

so when you call "getData(a)" then it means you are passing the address of the very first element as &a[0];

so inside you function getData() as

int getData(int *data)
{
    int i = 0;
    for(i; i < LENGTHOFINTARRAY(data); i++)
    {
        printf("%d, %d\n", LENGTHOFINTARRAY(data), data[i]);
    }

    return 1;
}

the data is just a pointer to integer & it gets the pointer or address of the a[0]; so your macro now sees data as pointer to int. which causes the result as u have gotten.

akp
  • 1,753
  • 3
  • 18
  • 26