Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this code well defined by using sizeof operator?

Tags:

arrays

c

sizeof

#include <stdio.h>

void test(int arr[]);

int main ()
{
    int *arr[3];
    int ar1[2] = { 1, 2 };
    int ar2[3] = { 3, 4, 5 };
    int vla[ar2[1]];
    arr[0] = ar1;
    arr[1] = ar2;
    arr[2] = vla;

    for  (int i = 0; i < 3; i++)
    {
        test(arr[i]);
    }
}

void test(int arr[])
{
    printf("%zu\r\n", sizeof(arr));
}

As the title say: is this valid? and if so, is there a way to make test() output different values by using sizeof on function argument handed in like on array?

like image 736
dhein Avatar asked Jan 13 '16 16:01

dhein


People also ask

What is sizeof () operator?

sizeof(int); The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding. Using the sizeof operator with a fixed-point decimal type results in the total number of bytes that are occupied by the decimal type.

Why is sizeof () an operator and not a function?

In C language, sizeof( ) is an operator. Though it looks like a function, it is an unary operator. For example in the following program, when we pass a++ to sizeof, the expression “a++” is not evaluated. However in case of functions, parameters are first evaluated, then passed to function.

What is the use of sizeof () operator in C ++? Give an example?

The sizeof() operator in C gives the size of its operand at compile time. It does not evaluate its operand. For example, int ar1[10]; sizeof(ar1) // output 40=10*4 sizeof(ar1[-1]) // output 4 int ar2[ sizeof(ar1) ]; // generate an array of 40 ints.

Is sizeof a function in C?

The sizeof() function in C is a built-in function that is used to calculate the size (in bytes)that a data type occupies in ​the computer's memory. A computer's memory is a collection of byte-addressable chunks.


1 Answers

Yes it is valid and will give the size of an int pointer (that's what the type of the arr parameter is, there are no array parameters in C) in bytes. 1

To get the size of an array in bytes with sizeof, the argument has to be an actual array, not a pointer.

Consequently, it's not possible to get the size of an array passed as a parameter inside a function without passing an extra parameter specifying the size.

So,

is there a way to make test() output different values by using sizeof on function argument handed in like on array?

no. (Without editing the function body.)

1 If you're wondering how it's possible to pass an array as a pointer parameter, it's because of the implicit array-to-pointer conversion, known as array decaying.

like image 140
emlai Avatar answered Oct 08 '22 11:10

emlai