pointer and NULL
drazenmozart (17)
Feb 4, 2013 at 12:29pm UTC
hi!,
i have a problem about how deleting the content-values of a pointer in c, without deleting the pointer and the memory that is allocated. what i do is:
1 2 3 4 5 6 7 8 9 10
IPs* ips = calloc(MAXIPS, sizeof (*ips));
for (i=0;i<MAXIPS;i++){
if ((ips+i)==NULL){
printf("not this time\n" );
}
else {
if ( (rc<=destr) || (rc<=0.1) ){
(ips+i)=NULL;
}
}
my problem is in line (ips+i)=NULL; where i get this "error: lvalue required as left operand of assignment"
thanks!!
EssGeEich (1007)
Feb 4, 2013 at 12:33pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
IPs* ips = calloc(MAXIPS, sizeof (*ips));
for (i=0;i<MAXIPS;i++)
{
if ((ips+i)==NULL)
{
printf("not this time\n" );
// Will never execute
// Unless you meant *(ips+i) == NULL
// Or also ips[i] == NULL
}
else
{
if ( (rc<=destr) || (rc<=0.1) )
{
(ips+i)=NULL;
// You meant *(ips+i) = NULL; ?
// Or also ips[i] = NULL; ?
}
}
}
drazenmozart (17)
Feb 4, 2013 at 1:17pm UTC
ok, didn't know that...so this is the way to increment by one sizeof struct? thanks
kbw (5517)
Feb 4, 2013 at 1:33pm UTC
(ips+i) just gives another address (pointer).
But you seem to need to check what that pointer points to, so you need to dereference it. The two ways you can do that are: *(ips + i) or ips[i] . They are equivalent, but the index form is more descriptive in my view.
Last edited on Feb 4, 2013 at 1:34pm UTC
drazenmozart (17)
Feb 4, 2013 at 1:44pm UTC
doesn't work with *(ips+i) 'error: incompatible types when assigning to type 'IPs' from type 'void *''
same thing with ips[i]
drazenmozart (17)
Feb 4, 2013 at 2:42pm UTC
one more question if i have :
1 2 3 4 5 6 7 8 9
typedef struct {
IP4h *ip4h;
}IPs;
typedef struct {
int ip_src;
}IP4h;
is the following right?:
1 2 3 4 5 6 7 8
main(){
IPs* ips = calloc(MAXIPS, sizeof (*ips));
for (i=0;i<MAXIPS;i++){
ips[i].ip4h->ip_src=5;
/*or*/
ips[i]->ip4h->ip_src=5;}
}
EssGeEich (1007)
Feb 4, 2013 at 3:02pm UTC
Not really.
Because you allocate memory for IPs, but not for IP4h.
You should do something like:
(You should use new/malloc instead too, I'll take this as if you are using C)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
IPs* ips = calloc(MAXIPS, sizeof (*ips));
for (unsigned int i = 0; i < MAXIPS; ++i)
{
ips[i].ip4h = calloc(1, sizeof ( *(ips[i].ip4h) ) );
}
// You can now use it.
for (unsigned int i = 0; i < MAXIPS; ++i)
{
free(ips[i].ip4h);
ips[i].ip4h = 0;
}
free(ips);
ips = 0;
drazenmozart (17)
Feb 4, 2013 at 8:01pm UTC
thanks, solved that problem... but now i get "error: expected expression before '=' token" at :
if (ips[i].ip4h!==0)
Last edited on Feb 4, 2013 at 8:08pm UTC
cPlusN00b (92)
Feb 4, 2013 at 8:16pm UTC
I think it's just "!=" not "!=="
drazenmozart (17)
Feb 6, 2013 at 12:33pm UTC
nope,that's not it.. but it's ok, for not null, i just wrote if (ips[i].ip4h) and hope this is right. At least it compiles without errors.
thank you all