Thread: malloc() with array of structures

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User khpuce's Avatar
    Join Date
    May 2003
    Posts
    165

    Question malloc() with array of structures

    Ok...its been two days now and I can't get it yet! I googled for long hours but couldn't find what exactly I was looking for. So, here it is -

    Say, I have a structure with only one element. (I'll add more elements to the structure once I get it to work!)

    Code:
    typedef struct
    {
       int roll;
    }STUDENT;
    Now when the program is run, I want the user to specify the number of students and then allocate the necessary memory using malloc(). So, I did this -

    Code:
        int num;
        REC *pt;
        pt= (REC *) malloc (num*sizeof(REC));  // I also tried this without casting!
    Now, I am having difficulties in stroing the values and then displaying those values back to the screen. I used the following code -

    Code:
    	printf("\n* * * * Enter roll no of students. * * * *\n");
    	for (i=0;i<num;i++)
    	{
    		printf("-->");
                   scanf("%d",(pt+i)->roll);
    	}
    
    	printf("\n* * * * Entered roll no. * * * *\n");
    	for (i=0;i<num;i++)
    	{	
                  printf("%d, ",*(pt+i)->roll);     //This is where the error occures!
    	}
    when I try do compile it, I get the error "invalid type argument of `unary *'".

    How can I solve this?

    P.S. I am using wxdev C++.
    Last edited by khpuce; 10-25-2010 at 11:25 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 60
    Last Post: 01-09-2009, 01:09 PM
  2. Initializing array of structures causing bus error
    By Aaron M in forum C Programming
    Replies: 5
    Last Post: 03-05-2006, 01:40 AM
  3. question about multidimensional arrays
    By richdb in forum C Programming
    Replies: 22
    Last Post: 02-26-2006, 09:51 AM
  4. filling an array of structures?
    By voodoo3182 in forum C Programming
    Replies: 9
    Last Post: 08-06-2005, 05:29 PM
  5. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM