Вопрос

Calling the function sum(int [], arr_size) in the statement

total = sum((int []){1,2,3,4,5}, 5);

a Compound Literal (int []){1,2,3,4,5} is passed as argument. It is clear that the length of array is determined by numbers of elements in literal(which is of-course 5 here). Then what is the need of passing 5 as another argument?

can't we define above function as

sum(int []) {....}

and then calling it as

total = sum((int []){1,2,3,4,5})

?

Это было полезно?

Решение 2

You can define sum that way and call it as shown in your example, but in that case you will not be able to determine the size of the array inside the function.

What you could do is declare sum as

int sum(int (*a)[5]) 
{
  ...
}

and then call it as

total = sum(&(int []){1,2,3,4,5});

But in this case you will be restricted to arrays of size 5 only. If you want to have a function that works with arrays of any size, you have to either pass the size from outside or reserve some sort of "terminator" element in your array

Другие советы

Your function sum is identical to sum(int *, size_t); the square brackets are just syntactic sugar. No arrays are passed at any point, and indeed you cannot pass arrays as function arguments in C. Thus there is no size information left in the "array" part of the function parameters, and the size must be passed separately.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top