Thread: allocating space dynamically for an array of structures

  1. #31
    Registered User
    Join Date
    Jan 2009
    Posts
    66
    Quote Originally Posted by Elysia View Post
    The question begs what you are trying to do?
    basically set up an array of structures and then use malloc to allocate space dynamically for that structure. I know i have made things difficult but - i am a beginner and trying to teach myself.

  2. #32
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    You have done, but what is the assignment for? What is it supposed to do?
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #33
    Registered User
    Join Date
    Jan 2009
    Posts
    66
    its not supposed to do anything - other than that question i.e. set up an array of structures and then use malloc to allocate space dynamically for that structure. thats it thats all its supposed to do.

  4. #34
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,343
    Quote Originally Posted by cus
    basically set up an array of structures and then use malloc to allocate space dynamically for that structure. I know i have made things difficult but - i am a beginner and trying to teach myself.
    Frankly, the first thing that you made difficult for yourself was in not following the instructions. Some teachers force students to use unreadable names, but your teacher asked you to use descriptive names: "for a structure of arrays, that must have the integer elements execution_time and process_number and a float element called average_time". Further more, it is clear that the structure type is to be named exec_time, not time. As such, I would expect:
    Code:
    typedef struct exec_time
    {
        int execution_time;
        int process_number;
        float average_time;
    } exec_time;
    Now, when you want to allocate n exec_time structures, I would expect something like this:
    Code:
    exec_time *exec_time_array;
    size_t n;
    
    /* Code to get the value of n */
    
    exec_time_array = malloc(n * sizeof(*exec_time_array));
    
    /* Code that uses the dynamically allocated array via exec_time_array */
    
    free(exec_time_array);
    (To be robust, you should check that the return value of malloc() is not NULL before using it, as would be the case if an allocation could not be performed.)
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #35
    Registered User
    Join Date
    Jan 2009
    Posts
    66

    thank you all.

    Thank you for your patience lazerlight - and everyone else - I obviously tried to over complicate things by asking the user to specify how many integers they would like to reserve, and as a result forgot about the objective. Here is what I have done.

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    typedef struct exec_time
    {
    	int execution_time;                
    	int process_number;                
    	float average_time;            
    }time; 
    
    time *exec_array;
    size_t n;
    
    int main()
    {
    exec_array = malloc(n *sizeof(exec_array));
    (*exec_array).execution_time=10;
    (*exec_array).process_number=9;
    (*exec_array).average_time=9.15;
    
    if(exec_array != NULL)
    	{
    		printf("%d %d %f\n",(*exec_array).execution_time,(*exec_array).process_number,(*exec_array).average_time);
    		free(exec_array);
    		return 0;
    	}
    			else 
    			{
    				printf("\nMemory allocation failed - not enough memory.\n");
    				return 1;
    			}

  6. #36
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    >>sizeof(exec_array)
    What is the size of a pointer? Not the size of the struct you want to allocate bytes for obviously!

    >>(*exec_array).execution_time=10;
    >>(*exec_array).process_number=9;
    >>(*exec_array).average_time=9.15;
    Hint: Try checking if the pointer is NULL BEFORE you assign or read anything from it.

    And (*exec_array).average_time is the same as exec_array->average_time. Repeat for the others.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #37
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,343
    Quote Originally Posted by cus
    I obviously tried to over complicate things by asking the user to specify how many integers they would like to reserve, and as a result forgot about the objective.
    Well, that makes the dynamic allocation useful, otherwise if n is sufficiently small you would just make the array a fixed size array

    Quote Originally Posted by cus
    Here is what I have done.
    Personally, I still think you should typedef the struct to exec_time, not time. More importantly, you are using malloc() pre-maturely. On the first line of the main() function, n is 0 since n has static storage duration. This means that you are allocating an array of zero size. You then access the first element of the array, but since the array has no elements, you are accessing the array out of bounds.

    I would expect something along these lines:
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    typedef struct exec_time
    {
        int execution_time;
        int process_number;
        float average_time;
    } exec_time;
    
    int main()
    {
        exec_time *exec_array;
        size_t n;
    
        printf("Enter a non-negative integer: ");
        /* Read in the input to n. */
    
        exec_array = malloc(n * sizeof(*exec_array));
    
        if (exec_array == NULL)
        {
            /* Print memory allocation failure error, and possibly exit immediately. */
        }
    
        /* Use exec_array */
        
        free(exec_array);
    
        return 0;
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #38
    Registered User
    Join Date
    Jan 2009
    Posts
    66
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    typedef struct exec_time
    {
    	int execution_time;                
    	int process_number;                
    	float average_time;            
    }exec_time; 
    
    int main()
    {
    
    exec_time *exec_array;
    size_t n;
    
    printf("Please enter a non-negative integer: ");
    scanf("%d", &n); 
    
    exec_array = malloc(n *sizeof(*exec_array));
    	if(exec_array == NULL)
    		{
    		printf("\nMemory allocation failed - not enough memory.\n");
    		}
    
    printf("%d %d %f\n",exec_array->execution_time,exec_array->process_number,exec_array->average_time);
    		free(exec_array);
    		return 0;
    	}
    I followed the bits of advice up until use exec_array part, obviously there is nothing in there now, but is that what you intended..... ?

  9. #39
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Does not work if malloc fails.
    And when are you going to learn indentation?
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #40
    Registered User
    Join Date
    Jan 2009
    Posts
    66
    Quote Originally Posted by Elysia View Post
    Does not work if malloc fails.
    And when are you going to learn indentation?
    I dont know how to do the indentation correctly - but i will look it up. But what do you mean does not work if malloc intended - have I not written it as you intended?

  11. #41
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Think up a scenario if malloc fails. Then step through your code in your mind with this scenario and watch what happens.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #42
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,343
    Quote Originally Posted by cus
    But what do you mean does not work if malloc intended - have I not written it as you intended?
    You probably should end the program immediately after printing the error message. Another option is to ask the user to enter a smaller number, and try again.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #43
    Registered User
    Join Date
    Jan 2009
    Posts
    66
    Quote Originally Posted by Elysia View Post
    Think up a scenario if malloc fails. Then step through your code in your mind with this scenario and watch what happens.
    Ok at this moment in time if malloc fails then the program will continue to execute and consequently run the following printf statement which we dont want.

    So therefore, we should make the program exit - I am unsure of how to do this.. would it be:
    Code:
    EXIT(0)
    Can i do this in the printf statement? Or do i do it afterwards?

  14. #44
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by cus View Post
    Ok at this moment in time if malloc fails then the program will continue to execute and consequently run the following printf statement which we dont want.
    Indeed not. Quite correct.

    So therefore, we should make the program exit - I am unsure of how to do this.. would it be:
    Code:
    EXIT(0)
    exit works fine, but in main, you can also use return since the program quits after the main function has finished executing.

    Can i do this in the printf statement? Or do i do it afterwards?
    What's the point of doing it afterwards if we don't want the print statement to run if malloc fails?

    Consequently, when writing the new code, use the same strategy to see if your logic is correct (works for small sections of code).
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #45
    Registered User
    Join Date
    Jan 2009
    Posts
    66
    ok this is what I have now - I have simply added return 1; and an else statement to execute the following printf for when 'exec_array' does not equal NULL. I have done this with the following code: Apologies for the lack of correct indentation - I have not mastered it yet!

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    typedef struct exec_time
    {
    	int execution_time;                
    	int process_number;                
    	float average_time;            
    }exec_time; 
    
    int main()
    {
    
    exec_time *exec_array;
    size_t n;
    
    printf("Please enter a non-negative integer: ");
    scanf("%d", &n); 
    
    exec_array = malloc(n *sizeof(*exec_array));
    	if(exec_array == NULL)
    		{
    		printf("\nMemory allocation failed - not enough memory.\n");
    		return 1;
    		}
    	else {
    printf("%d %d %f\n",exec_array->execution_time,exec_array->process_number,exec_array->average_time);
    		free(exec_array);
    		return 0;
    	}
    	
    }
    Is the exec_array not supposed to print any contents? - I am aware there is nothing there.

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, 04: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, 03:59 PM