Hardik
Hardik

Reputation: 11

Ask compiler to treat array as array(not pointer) when passing it to a function

I want to use sizeof operator after passing an array to a function but C language is considering it as pointer not an array.

Can we implement a functionality to solve this purpose ?

void foo(char array[])
{
    printf("sizeof array = %u\n", sizeof(array)); /* I know array is pointer here */
}

int main(void)
{
    int array[5];
    foo(array);
}

Upvotes: 1

Views: 113

Answers (3)

machine_1
machine_1

Reputation: 4454

You can't ask the compiler for that. It is not polite to do what you ask it to.

Instead you can add another parameter to your function definition to recieve the size of the array.

void foo(char array[], size_t array_size)
{
    printf("sizeof array = %zu\n", array_size);
}

int main(void)
{
    int array[5];
    foo(array, sizeof(array)) ;
}

Note: to print size_t use %zu in printf.

Note: to print number of elements, use: sizeof(array) / sizeof(*array)

Upvotes: 1

Mohammad Azim
Mohammad Azim

Reputation: 2953

Not possible and using an array subscript [] can be confusing to people not knowing that it will behave as a pointer. The approach that I take is to pass length as another argument or create a struct with pointer and length:

struct {
    char * buffer;
    size_t length;
} buffer_t;

I don't like the array in the struct or typedef approach as it restricts the data to a fixed size.

Upvotes: 1

bruno
bruno

Reputation: 32596

You can use a dedicated typedef, or as said in a remark an embedding struct :

#include <stdio.h>

typedef char A5[5];

typedef struct S {
  char a[5];
} S;

void foo(A5 a) /* of course can be "void foo(char a[])" but less clear */
{
  printf("%zu %zu\n", sizeof(A5), sizeof(a));
}

void bar(S s)
{
  printf("%zu\n", sizeof(s.a));
}


int main()
{
  A5 a;
  S s;

  foo(a);
  bar(s);
}

Of course in case of the typedef you need to use typeof on it rather than on the var being a char*

But all of that is a kind of hack, C is C ...

Upvotes: 0

Related Questions