Hi,

I'm trying to define a dynamic array that consists of an email address and a home address. How can I define them dynamically using malloc() in the below struct?

typedef struct entry{
	char name[40];			/* contains name */
	char phone_number[9];	/* contains phone number */
	struct entry *next ;	/* next is used to navigate through structures. */
} contact;

Recommended Answers

All 11 Replies

contact *newnode;
newnode = (contact*) malloc (sizeof(contact));

As in I do not know how long the e-mail address/home address is, hence I can't straightaway define it as

char emailaddress[40];

Hence, how can I go about making use of the malloc() statement to dynamically assign the memory based on the user input length of the email address/home address?

did you try my last post?

Yup, just saw. I have an Error: this declaration has no storage class or type specifier.. Where did I go wrong?

contact *email;
email = (contact*)malloc(sizeof(contact));

Apologies, this code should have gone into my main() as opposed to below the declaration of the struct(). Ok, got it! Thanks a lot!.. :)

Hmm, upon compilation of the program, I get this error:

1>c:\c:\...\test.c(20): error C2275: 'contact' : illegal use of this type as an expression
1> c:\c:\...\test.c(11) : see declaration of 'contact'
1>c:\...\test.c(20): error C2065: 'address' : undeclared identifier
1>c:\...\test.c(21): error C2065: 'address' : undeclared identifier
1>c:\...\test(21): warning C4047: '=' : 'int' differs in levels of indirection from 'contact *'

Code within the main() is as such:

contact *email;
	email = (contact*)malloc(sizeof(contact));

	contact *address;
	address = (contact*)malloc(sizeof(contact));

Ok, got it, apparently, I can't declare 2 contact *email and contact *address. I have to combine them together as such:

contact *email, *address;
	email = (contact*)malloc(sizeof(contact));
	address = (contact*)malloc(sizeof(contact));

hmm I tried compiling it in linux gcc and in pelles C using cygwin and didn't get any errors... even when separated

Hmm, no idea uh, I'm using Visual Studio 2010. When I made these changes, then only did it manage to compile without errors.

You can definitely declare variables in the middle of the code using gcc but not on the one provided by microsoft.
In the mircorsoft's one, we can only declare our variables at the beginning of our code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.