user4656543
user4656543

Reputation:

How to know the number of elements of an array while accessing through a pointer to that array

This is my code:

#include <stdio.h>

typedef struct{
int n;
char l;
} dat;

void printa(dat* x){
while(*x != NULL){
printf("%c %d\n",x->l,x->n);
x++;
}
}

int main(int argc,char* argv[]){
dat new[10]={
{4,'d'},
{7,'g'},
{3,'c'},
{6,'f'},
{2,'b'},
{5,'e'},
{1,'a'}
};
dat* x=new;
printa(x);
return 0;
}

I'm trying to display values through a pre-populated struct so that later I can make a sorting function on them.

The line containing while(*x != NULL) is problematic to the compiler. It states error: invalid operands to binary !=. I then changed it to while(*x) thinking that I got messed up with declaration of pointers, and the compiler complains with error: used struct type value where scalar is required. I then proceeded to change the line to while(x). The compiler did not complain yet, executing the code produced random values along with a segmentation fault.

I then proceeded to run the faulty compiled code through gdb and it states

Program received signal SIGSEGV, Segmentation fault. 0x0804838f in printa ()

I could easily fix my issue by modifying my code to match something like this:

void printa(dat* x){
int num=0;
while(num++ < 2){
printf("%c %d\n",x->l,x->n);
x++;
}
}

But I'd rather have the struct array go through completely (printing all elements) instead of stopping at a fixed number.

Upvotes: 0

Views: 122

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134326

No, what you want cannot be achieve directly. Once you use a pointer to point to an array, the pointer does not inherit any information abut the array size. So, you cannot pass the pointer to a function and expect to calcuate the valid length of the array through that pointer.

You have to follow either of the below methods

  1. Pass the length of the array as a second parameter to the function.
  2. Use a sentinel value in the array and check for the value in the function to stop accessing.

Upvotes: 2

ams
ams

Reputation: 25579

A pointer will never be NULL if it starts with a valid address and then gets incremented.

You need to modify your data so the loop knows when to stop.

  1. Use while (x->n != 0).

  2. Add {0, 0} at the end of your data initializer.

If zero is a valid value in your data then you'll need to adjust that, of course.

Upvotes: 0

Related Questions