norman
norman

Reputation: 5556

Finding the length of an array in C

I'm trying to find the length of an array of "header" structures that I defined (a header just holds a few informational int members, if that is relevant here). I attempt this by passing fl, the pointer to the start of the array, and idx, an index value that indicates where the proper fl_tails pointer is that is stationed at the end of the array (in other/repetitive words, 'fl_tails[idx]` is the pointer to the end):

int arr_size(header* fl, int idx){

  int cnt = 1; /* Anything passed guaranteed to have at least 1 */ 

  while(fl != fl_tails[idx]){
    fl++; 
    cnt++;
  }
}

I thought this would just advance the fl pointer and generate the count properly until the end was reached, but it goes into an infinite loop. I'm wondering if this is caused by something in this function or just something elsewhere that I need to find. When I printed the addresses of the beginning and end as unsigned ints, they seemed innocuous enough---things like 16777216 and 16777344, respectively. Maybe something is also wrong with my understanding of the header structure and its size/effect on steps?

Upvotes: 1

Views: 313

Answers (4)

Khaled Barazi
Khaled Barazi

Reputation: 8741

Remember that:

 while(fl != fl_tails[idx])

is equivalent to:

 while(fl != *(fl_tails + idx))

so what you are doing is comparing a pointer fl to an actual value since (fl_tails + idx) is a pointer and *(fl_tails + idx) is dereferencing this pointer to get the value it is pointing to.

so if you are just comparing pointer addresses to find the end of the array, I would change to:

while(fl != &fl_tails[idx])

so that you are comparing pointers to pointers.

As far as the values you got, remember that a pointer without a pointee can have a pointee holding an initialized value (some old value from some old program). I recommend seeing this video:

http://www.youtube.com/watch?v=f-pJlnpkLp0

Upvotes: 0

Aniket Inge
Aniket Inge

Reputation: 25695

The problem is fl_tails[idx] returns a different pointer type and fl is of a different pointer type. They will never point to the same location(unless they're inside a union) and so, I think, the program goes into an infinite loop.

Upvotes: 0

TheLazyChap
TheLazyChap

Reputation: 1902

I'm looking at your while loop, you're comparing a memory address against a value at an index. This will always evaluate to true. I believe this is why you're getting the infinite loop.

As for the length of the array, have you considered using the sizeof() operator/function.

Upvotes: 1

PQuinn
PQuinn

Reputation: 1022

You want to compare addresses, so:

while(fl != &fl_tails[idx])
            ^

Upvotes: 1

Related Questions