Reputation:
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
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
Upvotes: 2
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.
Use while (x->n != 0)
.
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