allocating space dynamically for an array of structures

This is a discussion on allocating space dynamically for an array of structures within the C Programming forums, part of the General Programming Boards category; Hi all I have been given the task of using malloc to allocate space dynamically for a structure of arrays, ...

  1. #1
    cus
    cus is offline
    Registered User
    Join Date
    Jan 2009
    Posts
    66

    allocating space dynamically for an array of structures

    Hi all I have been given the task of using malloc to allocate space dynamically for a structure of arrays, that must have the integer elements execution_time and process_number and a float element called average_time. Set up an array of structures and show how to access individual elements of the structures within the array. Then finally, use malloc to allocate space dynamically for a structure of the type structure exec_time. I think I am nearly there but I am receiving some errors.

    Which are:
    Question1.c: In function ‘main’:
    Question1.c:21: error: incompatible types in assignment

    Code:
             #include <stdlib.h>
             #include <stdio.h>
             typedef struct exec_time
        {
            int et;                
            int pn;                
            float at;            
        }time; 
    
          int qty, qty2, qty3, i;
         int getnumber();
         void printnumber();
         time pts[4] = {{4,8,0.75}, {5,10,0.00457}, {27,75,3.4}}; 
    
    int main()
    {
            time *numbers;
            getnumber();
            numbers = malloc( qty * sizeof(int) ); 
            if(numbers != NULL) 
    {
                   for(i=0; i<qty ; i++) numbers[i] = i+1;
                   for(i=0; i<qty ; i++) 
                   printf("%d ", numbers[i]);
                   printf("\n");
                           free(numbers); /*free allocated memory*/
                           printnumber();
                           return 0;
    }
               else {
                        printf("\nMemory allocation failed - not enough memory.\n");
                        return 1;}
    }
    
    
    int getnumber()
    {
         printf("\nHow many ints would you like to store for et? ");
         scanf("%d", &qty);
         printf("\nHow many ints would you like to store for pn? ");
          scanf("%d", &qty2);
         printf("\nHow many floats would you like to store for at? ");
         scanf("%d", &qty3);
                    qty = qty + qty2 + qty3; /*adds to total number of integers to be used with malloc and sizeof*/
                    return qty;
    }
    
    void printnumber() /*simply prints the value of the structure*/
    {
          printf("\n\nCode et= execution time, pn =process number, at = average time\n");
          printf("Variable 'time' at element 0 et: %d pn: %d at: %f\n",pts[0].et, pts[0].pn, pts[0].at);
          printf("Variable 'time' at element 1 et: %d pn: %d at: %f\n",pts[1].et, pts[1].pn, pts[1].at);
          printf("Variable 'time' at element 2 et: %d pn: %d at: %f at:\n\n",pts[2].et, pts[2].pn, pts[2].at);
    }
    Last edited by cus; 01-08-2009 at 09:43 AM.

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Why don't you indent your code?!!??

    I just posted an example of how to dynamically allocate an array of structs, if you want to look at that:
    Best method to alloc memory for string and desalloc.
    (post 47)
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    cus
    cus is offline
    Registered User
    Join Date
    Jan 2009
    Posts
    66
    Quote Originally Posted by MK27 View Post
    Why don't you indent your code?!!??

    I just posted an example of how to dynamically allocate an array of structs, if you want to look at that:
    Best method to alloc memory for string and desalloc.
    (post 47)
    indent my code? yes i know its scruffy.... my apologies - thanks for link.

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by cus View Post
    indent my code? how? thanks for link.
    Like this:
    Code:
    int main (int argc, char *argv[]) {
    	int len,i=0,x, fd=open("example.txt",O_RDONLY);
    	char string[128];	// should fit
    	struct template *example=malloc(sizeof(*example));  
    	 
    	while ((len=linein(fd,string))>0) {
    		string[len]='\0';
    		if (i>0) example=realloc(example,(i+1)*sizeof(*example));
    		fillstruct(&example[i],string);
    		i++;
    	}
    	close(fd);
    	/* now let's see if this worked */
    	for (x=0;x<i;x++) showstruct(&example[x]);
    	free(example);
    	return 0;  
    }
    Because you can see the individual BLOCKS OF CODE, this is much much much easier to decipher than:
    Code:
     
    int main (int argc, char *argv[]) {
    int len,i=0,x, fd=open("example.txt",O_RDONLY);
    char string[128];	// should fit
    struct template *example=malloc(sizeof(*example));  
    	 
    while ((len=linein(fd,string))>0) {
    string[len]='\0';
    if (i>0) example=realloc(example,(i+1)*sizeof(*example));
    fillstruct(&example[i],string);
    i++;
    }
    close(fd);
    /* now let's see if this worked */
    for (x=0;x<i;x++) showstruct(&example[x]);
    free(example);
    return 0;  
    }
    Remember, a code block is a real unit and not a poetic freedom.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    cus
    cus is offline
    Registered User
    Join Date
    Jan 2009
    Posts
    66
    sorry i dont understand how the link is an example
    Last edited by cus; 01-08-2009 at 09:24 AM.

  6. #6
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    ps. Your prof might not like my use of realloc. You should use two pointers in case you run out of memory:
    Code:
    if (tmp=realloc(example,(i+1)*sizeof(*example))) example=tmp;
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #7
    cus
    cus is offline
    Registered User
    Join Date
    Jan 2009
    Posts
    66
    no i dont want to use realloc, and the link you gave reads a little too complicated for me.

  8. #8
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by cus View Post
    sorry i dont understand how the link is a tutorial
    Well it's not. Here's the important bits for you condensed and annotated:
    Code:
    /* define our struct */
    struct template {
    	char item[20];
    	int cost;
    };
    
    
    int main () {
    	int i=0;
    	/* declare a typed struct pointer and allocate it enough memory for one instance */
    	struct template *example=malloc(sizeof(*example)), *tmp; //notice the extra pointer 
    	 
    	while (somecondition) {
    		/* the first one in the array already exists */
    		if (i>0) {
    			tmp=realloc(example,(i+1)*sizeof(*example));
    			if (tmp) example=tmp;  //because tmp will be NULL if no memory 
    		}
    		do anything with example[i];
    		i++;
    	}
    }
    ps. If you try and indent your code, I might try and read it.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  9. #9
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by cus View Post
    no i dont want to use realloc, and the link you gave reads a little too complicated for me.
    If you do not use realloc, you cannot really allocate the space dynamically (in the sense of expanding the array), although I guess malloc is "dynamic allocation". In that case you are just doing this once:
    Code:
    int NumberOfStructs
    struct template *example;
    example=malloc(NumberOfStructs*sizeof(*example));
    This works because a pointer of type struct template is typed to be a struct template, so sizeof returns the number of bytes one such struct requires.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  10. #10
    cus
    cus is offline
    Registered User
    Join Date
    Jan 2009
    Posts
    66
    Quote Originally Posted by MK27 View Post
    ps. If you try and indent your code, I might try and read it.
    Look up - is that ok?

  11. #11
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by cus View Post
    Look up - is that ok?
    Much better. The first thing that I noticed is that you do this
    Code:
    numbers = malloc( qty * sizeof(int) );
    Which of course should be:
    Code:
    numbers = malloc(qty*sizeof(time));
    OR
    numbers = malloc(qty*sizeof(*numbers));
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  12. #12
    cus
    cus is offline
    Registered User
    Join Date
    Jan 2009
    Posts
    66
    either way i still get the same errors message:

    Question1.c: In function ‘main’:
    Question1.c:21: error: incompatible types in assignment

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,165
    What is your current code?
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    cus
    cus is offline
    Registered User
    Join Date
    Jan 2009
    Posts
    66
    the one identical to the first post

  15. #15
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by cus View Post
    either way i still get the same errors message:

    Question1.c: In function ‘main’:
    Question1.c:21: error: incompatible types in assignment
    Post line 21. In your first post it's just "{", so there must be an extra space or something. An incompatible type error is usually when you supply the wrong kind of variable to a function.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Page 1 of 5 12345 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 11-26-2008, 10:25 AM
  2. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 05:15 AM
  3. dynamically allocating a 2dim array
    By agerealm in forum C++ Programming
    Replies: 14
    Last Post: 03-10-2004, 02:40 PM
  4. 2d array of structures
    By spudtheimpaler in forum C Programming
    Replies: 2
    Last Post: 03-01-2004, 03:17 PM
  5. someone who is good at finding and fixing bugs?
    By elfjuice in forum C++ Programming
    Replies: 8
    Last Post: 06-07-2002, 04:59 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21