Thread: dynamic array

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    96

    dynamic array

    hi i have a code here iam trying to dynamic allocate memory for my structure how can i do that i try doing it this way but it wont compile. helpp please
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<conio.h>
    
    struct student
    {
           char name[20];
           int id;
           
    };
    
    main()
    {
          
          struct student *info;
          int x;
          
          printf("how many student");
          scanf("%i",&x);
          info=(struct*)malloc(sizeof(struct)*x);
          
          
    
    getch();
    }

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    I don't know about anything other but try this:

    Code:
    int main()
    Devoted my life to programming...

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    "struct*" doesn't make any sense; and in any event, the result of malloc should not be cast in C.

  4. #4
    Registered User
    Join Date
    Feb 2010
    Posts
    96
    so should i typedef it

  5. #5
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    It should be nonexistent. You should not have anything between the "=" and the "malloc" (except maybe a space).

  6. #6
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    How about telling the compiler WHICH struct you want to calculate the sizeof:

    Code:
    info=malloc(sizeof(struct student)*x);
    /*info now points to info[0], the start of an array of x students */

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by claudiu View Post
    How about telling the compiler WHICH struct you want to calculate the sizeof:
    How about not?
    Code:
    info = malloc( x * sizeof *info );

    Quzah.
    Hope is the first step on the road to disappointment.

  8. #8
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Quote Originally Posted by quzah View Post
    How about not?
    Code:
    info = malloc( x * sizeof *info );

    Quzah.
    Of course, that works as well. I don't usually do it that way because it's less readable in a long code IMO, particularly if you have the declaration far from where you are allocating memory.

  9. #9
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by claudiu View Post
    Of course, that works as well. I don't usually do it that way because it's less readable in a long code IMO, particularly if you have the declaration far from where you are allocating memory.
    I'm not sure I follow that. If I see the line
    Code:
    a = malloc( n * sizeof *a );
    and I know it compiles, there is enough information to know that (1) a is a pointer to some type and (2) this line allocates memory for n objects of that type.

    It's true this line does not educate me about what a points at, but that is not necessary for an understanding of what this line does.

    I may be missing your point. If so, what have I missed?

    I'd also argue that, if the declaration is "far from where you are allocating memory" that there are more significant concerns related to understanding the code than grasping the nature of a malloc() call. While specific guidelines vary in practice, a general theme is small and self-contained functions are easier to understand than big functions. If you stick to that theme, there would not be much separation between a variable declaration and usage of that variable.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  10. #10
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Quote Originally Posted by grumpy View Post
    I'm not sure I follow that. If I see the line
    Code:
    a = malloc( n * sizeof *a );
    and I know it compiles, there is enough information to know that (1) a is a pointer to some type and (2) this line allocates memory for n objects of that type.

    It's true this line does not educate me about what a points at, but that is not necessary for an understanding of what this line does.

    I may be missing your point. If so, what have I missed?

    I'd also argue that, if the declaration is "far from where you are allocating memory" that there are more significant concerns related to understanding the code than grasping the nature of a malloc() call. While specific guidelines vary in practice, a general theme is small and self-contained functions are easier to understand than big functions. If you stick to that theme, there would not be much separation between a variable declaration and usage of that variable.
    That may be so, but you may be reallocating memory for a variable, and in that case you can have the declaration pretty far away from the re-allocation. Not to mention, cases where pointers are global variables in some other header you are including.

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    > particularly if you have the declaration far from where you are allocating memory.
    So
    Code:
    int *p;
    // lots of code
    p = malloc( 10 * sizeof(int) );
    If it's a long way away, how will you cope with this bug-trap?
    You decide ints are no longer enough, so you want a bigger type.
    Code:
    long int *p;
    // lots of code
    p = malloc( 10 * sizeof(int) );
    OOPS - you're no longer allocating the right amount of memory!

    You're not going to get a compiler warning for getting the size wrong.
    Unless you get lucky, and it crashes on the first test, this kind of bug can easily disappear for months or years before resurfacing.

    Getting the compiler to use the variable to obtain the size information saves you from having to maintain the same information in multiple locations.
    Or from having to worry about what it means if such information appears to be different.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  12. #12
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Quote Originally Posted by Salem View Post
    > particularly if you have the declaration far from where you are allocating memory.
    So
    Code:
    int *p;
    // lots of code
    p = malloc( 10 * sizeof(int) );
    If it's a long way away, how will you cope with this bug-trap?
    You decide ints are no longer enough, so you want a bigger type.
    Code:
    long int *p;
    // lots of code
    p = malloc( 10 * sizeof(int) );
    OOPS - you're no longer allocating the right amount of memory!

    You're not going to get a compiler warning for getting the size wrong.
    Unless you get lucky, and it crashes on the first test, this kind of bug can easily disappear for months or years before resurfacing.

    Getting the compiler to use the variable to obtain the size information saves you from having to maintain the same information in multiple locations.
    Or from having to worry about what it means if such information appears to be different.
    Obviously, that may be the case. I was just stating a personal preference. If you change the type of the variable and you overlook the memory allocation part for that variable, then excuse me, but you have bigger problems than coding styles. I think that in a long program where you are allocating memory for A LOT of variables it makes the code easier to read(especially for another developer) if you state the actual data type inside the allocation rather than just passing the pointer itself and making the coder ask himself:

    Ok what the hell is this pointer? Oh, how convenient. It's declared in SOME OTHER FILE!

  13. #13
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by claudiu View Post
    Obviously, that may be the case. I was just stating a personal preference. If you change the type of the variable and you overlook the memory allocation part for that variable, then excuse me, but you have bigger problems than coding styles.
    No. The point of the "a = malloc(n * sizeof *a)" technique is that it works correctly regardless of what type a points at.

    Using another technique is just an invitation to forget to update the malloc() call when the type of a changes.
    Quote Originally Posted by claudiu View Post
    I think that in a long program where you are allocating memory for A LOT of variables it makes the code easier to read(especially for another developer) if you state the actual data type inside the allocation rather than just passing the pointer itself and making the coder ask himself:

    Ok what the hell is this pointer? Oh, how convenient. It's declared in SOME OTHER FILE!
    The coder is going to need to ask that question for any use of the pointer after the malloc() call anyway.

    Your technique would be misleading in this circumstance.
    Code:
    long *x;      /*   We used to have this as a short  */
    
    /*  and later   */
    
    x = malloc(n*sizeof short);    /*   Whoops!   This does not match declaration of x */
    
    /*   Assume x points to a short ... after all, the malloc() call here tells us that  */
    Yes, it is inconvenient to have to check the type of x to use it. But using a technique that allows the programmer to misinform him/her self is not just inconvenient, it is folly.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  14. #14
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    The whole point is that you don't really need to know what the type of the pointer is. Using malloc to show the type might be a good idea, but surely is not the general case.
    You might want to show how many bytes you allocate, in which case the sizeof(type) is more convinient.

    In any case, grumpy's method should be your default choice and has more "serious" advantages.

  15. #15
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Quote Originally Posted by grumpy View Post
    No. The point of the "a = malloc(n * sizeof *a)" technique is that it works correctly regardless of what type a points at.

    Using another technique is just an invitation to forget to update the malloc() call when the type of a changes.


    The coder is going to need to ask that question for any use of the pointer after the malloc() call anyway.

    Your technique would be misleading in this circumstance.
    Code:
    long *x;      /*   We used to have this as a short  */
    
    /*  and later   */
    
    x = malloc(n*sizeof short);    /*   Whoops!   This does not match declaration of x */
    
    /*   Assume x points to a short ... after all, the malloc() call here tells us that  */
    Yes, it is inconvenient to have to check the type of x to use it. But using a technique that allows the programmer to misinform him/her self is not just inconvenient, it is folly.
    I disagree. Certainly, I see the advantages of that method, however there are several things I would like to mention here:

    Firstly, as I said previously, x = malloc(n * sizeof(int)) improves the READABILITY of the code which is an undeniable qualitative aspect of the program. I think this is more important than writing code so as to prevent yourself from making mistakes that you should not be making in the first place. (i.e. your long-short example) Simply put, the quality of the code, which is also reflected by its readability cannot be sacrificed for the sake of reducing the time you spend debugging your program.

    Secondly, a good programmer will spend a considerable amount of type designing the data structures and data types used in his program well before he starts typing code. Consequently, changes in data types should not be too frequent while developing your code. Data representation is a design decision first and foremost. If you design your program well, you will know before you type that x should be a long and not a short. I personally am more old school and believe in the principle of thinking before typing code, rather than jumping on the keyboard and figuring things out on the way.

    Thirdly, the importance of malloc is that it allocates memory, however ironically, using:
    x=malloc(n * sizeof *x) gives you absolutely NO IDEA about how much memory you are allocating. All you know is that you are allocating n slots for whatever type x is and that is simply insufficient.

    Lastly, the R&K book uses this approach on malloc() and not the one with the pointer. This is not a reason per se, however I think it's important to learn from how the developers of the language use it.
    Last edited by claudiu; 04-10-2010 at 07:44 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic Array Resizing
    By dld333 in forum C++ Programming
    Replies: 13
    Last Post: 11-04-2005, 12:13 AM
  2. need help with dynamic array syntax
    By soldyne in forum C Programming
    Replies: 3
    Last Post: 10-11-2005, 01:59 PM
  3. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  4. 2D dynamic array problem
    By scsullivan in forum C Programming
    Replies: 3
    Last Post: 12-30-2002, 10:02 PM
  5. Dynamic array allocation and reallocation
    By purple in forum C Programming
    Replies: 13
    Last Post: 08-01-2002, 11:48 AM