structure's memory layout in the function?

N

Narendra

void function1(void *);
void main()
{
int size_offset = 0;
typedef struct
{
int a;
int b;
int c;
char ch;
}A;

A *pst = NULL;
pst = (A*)malloc(sizeof(A)*1);

function1((void*)pst);
}
void function1(void *pStr)
{
// As i need to intialize the structure members. i want to access it's
me
mbers.
// How can i know the structure's
// memory layout in this function?

//Conditions:
//1. i do not want to declare the structure as global or static.
//2. I will pass the structure pointer as void pointer.

}
 
A

Alf P. Steinbach

* Narendra:
void function1(void *);

Avoid void.

void main()

Invalid in C and C++, and has never been valid.

{
int size_offset = 0;
typedef struct
{
int a;
int b;
int c;
char ch;
}A;

No need to use a typedef in C++.

Also, reserve all uppercase names for macros.

A *pst = NULL;
pst = (A*)malloc(sizeof(A)*1);

Use 'new', not 'malloc'.

Don't use casts.

function1((void*)pst);

Don't use casts.

}
void function1(void *pStr)
{
// As i need to intialize the structure members. i want to access it's
me
mbers.

Use a constructor to initialize memebers.

// How can i know the structure's
// memory layout in this function?

//Conditions:
//1. i do not want to declare the structure as global or static.
//2. I will pass the structure pointer as void pointer.

Since you didn't even get 'main' right, it's doubtful that there are any
good or even meaningful reasons for these conditions.
 
S

Stuart Redmann

Narendra said:
void function1(void *);
typedef struct
{
int a;
int b;
int c;
char ch;
}A;
// As i need to intialize the structure members. i want to access it's
// members.
// How can i know the structure's
// memory layout in this function?

//Conditions:
//1. i do not want to declare the structure as global or static.
//2. I will pass the structure pointer as void pointer.

You can't. Since you only pass a void* pointer to your function, you
cannot extract any information about the type that is pointed to. Note
that unlike (for example) Java no run-time information about the types
are available in C++. If the only task you have in mind is
initialization, you can simply add a constructor to your struct:

struct A
{
int a;
int b;
int c;
char ch;
A ()
: a (0), b (0), c (0), ch (0)
{}
};

So whenever we declare an variable of type A, its members will be
initialized automatically.

Regards,
Stuart
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top