0

How do we get the number of elements in an arraywithout using sizeof. In any case sizeof does not get me the correct number of elemnts so I want to implement my self without using sizeof.

I tried to run using sizeof and it doesn't print the correct number of elements in an array.

int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < n; i++){
printf("%s\n", arr[i]);
}   
// to check if the noof elts in the arr is correct 
printf("%d\n", n);
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Yemi Bold
  • 196
  • 1
  • 4
  • 4
    You can't do that. What is `arr` in your example? The code in your question looks OK to me, provided `arr` is actually an array like `int arr[10]`. Don't describe it, but [edit] mand add the corrresponding declaration. Also read this [mcve]. – Jabberwocky Jan 11 '22 at 11:28
  • 2
    Please [edit] your question and create a [mre], i.e some example code we can compile and run which demonstrates a case where `sizeof` does not work as you expect. My guess is that you pass an array to a function and try to use `sizeof` inside the called function. – Bodo Jan 11 '22 at 11:30
  • 1
    If `arr` is a parameter of a function, it is never an array but decays to a pointer. In that case `sizeof` will not work for you. – Gerhardh Jan 11 '22 at 11:30
  • [`sizeof` isn't a function but an operator](https://stackoverflow.com/q/1393582/995714) because you can use `sizeof x` without parentheses – phuclv Jan 11 '22 at 11:31
  • @phuclv it's rather the other way round – Jabberwocky Jan 11 '22 at 11:32
  • @Yemi Bold If the character array contains a string then use the function strlen. – Vlad from Moscow Jan 11 '22 at 11:35
  • Does this answer your question? [Determine size of dynamically allocated memory in C](https://stackoverflow.com/questions/1281686/determine-size-of-dynamically-allocated-memory-in-c) – Karol T. Jan 11 '22 at 11:40

1 Answers1

1

When you use an array as an argument in a function call, it is automatically converted to a pointer to its first element. The C standard does not provide any means for finding the size of an array given only a pointer to its first element.

For a function to know the size of an array that is passed to it in this way, you must pass the size as a separate argument or must provide the function some other way of knowing the size, such as including a sentinel value to mark the end. (For example, the null character that marks the end of a string is a sentinel.)

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312