malloc

H

Horst Kraemer

i am having a pointer testptr to a structure test

struct
{
int a;
char b[10];
}test;

test *testptr;

This is illegal sytax. You may use

struct test
{
int a;
char b[10];
};

struct test *testptr;

or

typedef
struct
{
int a;
char b[10];
}test;

test *testptr;

or

typedef
struct anything
{
int a;
char b[10];
}test;

test *testptr;
I am doing malloc for the pointer to have memory for an array of 3
structures like below:
testptr=(testptr)malloc(sizeof(test)*3);

Again illegal syntax.

testptr=(test*)malloc(sizeof(test)*3);

would be legal but the cast (test*) isn't necessary in C.
Now how can i get to know that testptr is allocated memory for an
array of 3 strcture from the testptr variable?

testptr=malloc(sizeof *testptr *3);
if (testptr==0) { /* couldn't allocate memory */ }
or
if (testptr==NULL) { /* couldn't allocate memory */ }
or
if (!testptr) { /* couldn't allocate memory */ }

Which form you use is a matter of style. malloc returns a null pointer
if the requested memory size couldn't be allocated.

Regards
Horst
 
H

harish

i am having a pointer testptr to a structure test

struct
{
int a;
char b[10];
}test;

test *testptr;


I am doing malloc for the pointer to have memory for an array of 3
structures like below:
testptr=(testptr)malloc(sizeof(test)*3);

Now how can i get to know that testptr is allocated memory for an
array of 3 strcture from the testptr variable?
 
U

user

harish said:
i am having a pointer testptr to a structure test

struct
{
int a;
char b[10];
}test;


test is a variable and hence the below line will fail. You can use the below
code.
struct test
{
int a;
char b[10];
};

struct test *testptr;
test *testptr;

this is wrong
I am doing malloc for the pointer to have memory for an array of 3
structures like below:
testptr=(testptr)malloc(sizeof(test)*3);

testptr = malloc (sizeof *testptr *3);
Now how can i get to know that testptr is allocated memory for an
array of 3 strcture from the testptr variable?

by checking the value of testptr. If it is non null then u have got what u
requested for

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,162
Latest member
GertrudeMa
Top