like this:
                  
                  
                  int my_funcie(int *arr);
                  
                  
                  
                  
                  
                  It takes an array of integers, and let's say it prints the array's elements
                  
                  
                  
                  
                  
                  The problem is I want to use a for loop to print elements, and I don't want to hardcode the condition
                  
                  
                  For example
                  
                  
                  
                  
                  
                  for(int index = 0; index < array_length; index++)
                  
                  
                  
                  
                  
                  here, the array_size is the problem
                  
                  
                  According to this StackOverflow answer
                  
                  
                  
                  
                  
                  It should work using this piece of code:
                  
                  
                  int array_length = sizeof(arr) / sizeof(arr[0])
                  
                  
                  
                  
                  
                  I put this inside my my_funcie function, but it doesn't give me the proper result
                  
                  
                  For example It's saying the array with 5 integer elemnts (sizeof(arr)) is 8 and the sizeof(arr[0]) is 4
                  
                  
                  It does  8/4 and gets 2 as the array_length
                  
                  
                  
                  
                  
                  What am I doing wrong?
                  
                  
                  The same method works pretty well where I defined the array itself
                  
                  
                  
                  
                  
                  I'm using C and gcc 9.2.0 btw
                  
                  
                
It doesn't work this way if you're getting the array as a function parameter. Go through the ss posted by John it'll explain this in detail. Instead of array you can use vectors. Personally I prefer vectors over arrays plus vectors have their own size() function which will give you an exact count of the number of elements present inside it.
rewrite the function signature as int my_funcie(size_t size, int arr[size])
Jens Gustedt's Modern C has multiple paragraphs about the difference between arrays and pointers. you should read them. the book is linked in the pinned message.
Обсуждают сегодня