pointer and NULL

Feb 4, 2013 at 12:29pm
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!!
Feb 4, 2013 at 12:33pm
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; ?
		}
	}
}
Feb 4, 2013 at 1:17pm
ok, didn't know that...so this is the way to increment by one sizeof struct? thanks
Feb 4, 2013 at 1:33pm
(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
Feb 4, 2013 at 1:44pm
doesn't work with *(ips+i) 'error: incompatible types when assigning to type 'IPs' from type 'void *''

same thing with ips[i]
Feb 4, 2013 at 2:42pm
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;}
}
Feb 4, 2013 at 3:02pm
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;
Feb 4, 2013 at 8:01pm
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
Feb 4, 2013 at 8:16pm
I think it's just "!=" not "!=="
Feb 6, 2013 at 12:33pm
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
Topic archived. No new replies allowed.