pointer and NULL

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

same thing with ips[i]
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;}
}
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;
thanks, solved that problem... but now i get "error: expected expression before '=' token" at :
if (ips[i].ip4h!==0)
Last edited on
I think it's just "!=" not "!=="
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.