Thread: Variable size arrays

  1. #1
    Registered User
    Join Date
    Sep 2002

    Variable size arrays

    Hi all, I'm having trouble with arrays ( Yes I'm new to C )

    Here is what I want to do in a nutshell:

    #include <stdio.h>

    main ()
    printf("Please input the size of the array you want");
    int arrsize;
    int myarray [arrsize];

    I can't do that so I've been experimenting with malloc and have come up with this:

    int arrsize;
    int *numptr;
    numptr = (int *) malloc (arrsize);

    This is where I'm stuck, now I've got this chunk of memory ( is it the right size? ) how can I make it so it acts as an array.

    myarray [0]
    myarray [1]
    myarray [arrsize]

    Thanks in advance for any help.

  2. #2
    Registered User moi's Avatar
    Join Date
    Jul 2002
    numptr = (int *) malloc (sizeof (int) * arrsize);
    hello, internet!

  3. #3
    Registered User
    Join Date
    Sep 2002
    thanks, will I then be able to use that memory space as an array. If so how do I access it?

    I want to add numbers to each each member of the array like this ideally:

    int i;
    for (i=0;i<=arrsize;i++) {
    myarray[i] = i;

    Any ideas

  4. #4
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Pointers and dynamic allocation etc

    That's the full details anyways, but there are also plenty of examples on here if you look for them.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  5. #5
    Registered User
    Join Date
    Sep 2002
    Good link thanks, I've sorted my problem now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need some help...
    By darkconvoy in forum C Programming
    Replies: 32
    Last Post: 04-29-2008, 03:33 PM
  2. variable array size
    By shuo in forum C++ Programming
    Replies: 39
    Last Post: 01-29-2008, 06:39 PM
  3. An exercise in optimization
    By Prelude in forum Contests Board
    Replies: 10
    Last Post: 04-29-2005, 03:06 PM
  4. size of integer arrays
    By steve8820 in forum C++ Programming
    Replies: 2
    Last Post: 03-06-2002, 07:31 PM