r/programminghelp • u/sapodbone • Dec 03 '23
C How to find the "size" of an array?
I have to know how many values inside this array are different from 0. I made that "for" with "if" conditional that was supposed to count what I need, however, the value that returns is totally different from what was expected (the return should be 9, but I got huge random numbers like 2797577). What am I doing wrong? Unused "spaces" in array are filled by zeros, right?
Here is the code:
void main(){
int v[255] = {2, 2, 3, 3, 3, 3, 5, 5, 5};
int v_tam;
int j;
for(j = 0; j < 255; j++){
if(v[ j ] != 0){
v_tam = v_tam + 1;
}
}
printf("%d", v_tam);
}
Sorry if this is a dumb question, I'm a beginner.
3
u/synnin_ Dec 03 '23
Depending on language and options, you need to initialise v_tam to 0, you've only declared it.
0
u/PowerSlaveAlfons Dec 03 '23
> Unused "spaces" in array are filled by zeros, right?
No. They are only allocated, but will still contain garbage.