0
The idea is to create a function that, given a one-dimensional array/vector, returns the number of elements present in that array/Array:
#include<stdio.h>
#include<stdlib.h>
#define MAX 6
#define TXT 20
int arraySize(char array[][TXT]);
int main(){
char array[MAX][TXT]={"Test0", "Test1", "Test1", "Test2", "Test3", "Test3"};
printf("\n Main: [%d]\n Func: [%d]\n\n", sizeof(array)/sizeof(array[0]), arraySize(array));
return 0;
}
int arraySize(char array[][TXT]){
return sizeof(array)/sizeof(array[0]);
}
The point here is that the main function works perfectly, so when done in an auxiliary function, the result, even using the same logic, is incorrect; I wonder if anyone can help me in this dilemma, I believe it has to do with the type of parameter passage, but I tried using pointers and the error persists.
OBS.: Using the MAX constant is not an option, since, not necessarily, I will know the value of MAX; the idea is, precisely, to discover the number of elements of this vector to, for example, use it as an argument of an iterator.
Its array is of static size so it will always have the same size in memory. It makes no difference whether you are using memory or not, you have allocated a char[MAX][TXT] matrix. To do what you want you must mark which addresses of the array you are not using, e.g. by checking NULL. Then you change your counting function so that it counts the number of valid strings in the array.
– aviana
I thought of that possibility, the question is, the way it is, run the line
sizeof(array)/sizeof(array[0])
inside and outside the main with the same vector returns different results. In the above execution example it returns 6 inside the main (correct number of elements present in the vector) and in the functionint arraySize(char array[][TXT])
it returns 0. This occurs because inside the mainsizeof(array)
returns 120 (20 * the number of elements of the vector), however the same function executed in the functionint arraySize(char array[][TXT])
returns 4,– L.Bravo
following the execution logic, the main fara 120/20=6 while the other function will 4/20=0, the question is why the other function returns 4 when I do
sizeof(array)
– L.Bravo
So, sizeof is an operator that returns the value during COMPILATION and not during EXECUTION. Its code in the arraySize function defines another variable with a different type array name than the main array. Hence the compiler n knows which array size in the function (pq vc defined the array type in char[][MAX]) and returns a default value of 4 bytes.
– aviana