dynamic array

This is a discussion on dynamic array within the C Programming forums, part of the General Programming Boards category; hi i have a code here iam trying to dynamic allocate memory for my structure how can i do that ...

  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
    1,625
    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,185
    "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,185
    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,666
    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, Sunshine, and read this, this, and this before posting again.

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,852
    > 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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  11. #11
    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!

  12. #12
    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.

  13. #13
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    I usually do it the way claudiu does, and that's what I'm used to, but I agree there are some obvious advantages to the alternative.
    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

  14. #14
    Registered User
    Join Date
    Jun 2005
    Posts
    6,666
    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, Sunshine, and read this, this, and this before posting again.

  15. #15
    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.

Page 1 of 3 123 LastLast
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, 02:59 PM
  3. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 05: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, 12:48 PM

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