C POINTERS

Hi,
Do i need to free the pb->pchr pointer?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>
#include <stdlib.h>

struct mystruct {
	int a;
	char *pchr;
};
typedef struct mystruct * pmystruct;
pmystruct getpstruct() {
	pmystruct temp=(pmystruct)malloc(sizeof(pmystruct*)) ;
	return temp;
}

int main(int argc, char **argv){
	pmystruct pb= getpstruct() ;
	pb->a = 8;
	char *pchr = "TEST STRING";
	pb->pchr = pchr;

	++pb->a;
	printf ("\nThe value of b->a is %i ",pb->a) ;
	printf ("\nThe value of b->pchr is %s ",pb->pchr) ;

	free(pb) ;
	pb = NULL;
	return 0;
}
You did not allocate in using malloc(), so no.
i have a question in line 10: pmystruct temp=(pmystruct)malloc(sizeof(pmystruct*)) ;
shouldn't you use sizeof(pmystruct);
Last edited on
shouldnt u use pmystruct temp = (pmystruct)malloc(sizeof(mystruct)); ?
And shoulnd't you first alocate memory to pb->pchr before assigning a value to it?
There's so many things wrong here, it's hard to know where to start. Just go back to the beginning of your book's chapter on pointers and start over.
Topic archived. No new replies allowed.