-2

When I run these lines in main to count the no of elements in an array it gives desired output but inside my function I am getting warning. I am beginner in C language.

void func(int arr[]){
    int n = sizeof(arr)/sizeof(arr[0]);
}

int main(){
    int a1[]={1,2,3,4,5,6};
    func(a1);
    return 0;
}

The message it gives is:

warning: 'sizeof' on array function parameter 'arr' will return size of 'int *' [-Wsizeof-array-argument]
     int n = sizeof(arr)/sizeof(arr[0]);
                   ^
temp2.c:3:15: note: declared here
 void func(int arr[]){

I wanted to get the number of elements in an array given to function and it works fine in main function.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • the warning is correct. You cannot use `sizeof` in this way to get the size of the array. `arr` is just a pointer – 463035818_is_not_an_ai Jul 03 '23 at 11:52
  • Does this answer your question? [Finding length of array inside a function](https://stackoverflow.com/questions/17590226/finding-length-of-array-inside-a-function) – BoP Jul 03 '23 at 11:54
  • Does this answer your question? [Find the Size of integer array received as an argument to a function in c](https://stackoverflow.com/questions/25680014/find-the-size-of-integer-array-received-as-an-argument-to-a-function-in-c) – Korosia Jul 03 '23 at 11:54

2 Answers2

0

you cant do it with sizeof operator in C. Either you need to pass the size into the function as a separate integer argument or you have to have special character to signal the end of the useful items in the array or the interested elements of the array. like '\0' for strings.

-2

Long story short your answer is here due to this question technically already been answered:

C sizeof a passed array

Monogeon
  • 346
  • 1
  • 9
  • 4
    If a question already has an answer somewhere else, please raise a flag and link the duplicate question. Do not answer duplicate questions, especially not with just a link to another question. – Yksisarvinen Jul 03 '23 at 12:31
  • noted. Wasn't entirely sure what to do. thanks – Monogeon Jul 04 '23 at 16:35