Thread: initializing arrays with user input

  1. #1

    Angry initializing arrays with user input

    My assignment is to ask the user what size array they want. The compiler keeps saying, constant expression required in function main().
    code is:
    cout<<"Enter size of array:"<<endl;
    int array1[x];

  2. #2
    Code Warrior
    Join Date
    Nov 2001
    I think this is not possible. You must define "char string[100];" and then you can enter how many arrays will you use.
    Current projects:
    1) User Interface Development Kit (C++)
    2) HTML SDK (C++)
    3) Classes (C++)
    4) INI Editor (Delphi)

  3. #3
    the only way for doing this is with dynamic memory allocation( I think).
    char *string;
    cout<<"Enter size of array:"<<endl; 
    string= (char *) malloc(sizeof(char)*x);
    free(string);//do not forget this, you have to free the memory
    A better way of doing it is with "new" and "delete"
    but I can't give you an example because I only use them 1 or 2.
    look them up and use them instead of malloc

  4. #4
    the Corvetter
    Join Date
    Sep 2001
    You can use realloc. That way, you just realloc after every input.
    1978 Silver Anniversary Corvette

  5. #5
    Linguistic Engineer... doubleanti's Avatar
    Join Date
    Aug 2001
    your compiler might register memory frees as an atexit command... so check...
    hasafraggin shizigishin oppashigger...

  6. #6
    new and delete are C++ operators. This is the C board. also in C you do not need to cast malloc(), in fact it is better if you don't.
    Furthermore, if you have GCC or a C99 compatible compiler you can use you original code.

  7. #7
    Registered User
    Join Date
    Sep 2001
    Arrays must know how long they are at compile-time. If you want to allocate a certain amount of memory based on run-time information, you'll have to use dynamic memory allocation...
    #include <stdlib.h>
    int main ()
     int N;
     int * a;
     printf("Enter size of array: ");
     scanf ("%d", &N);
     a = malloc (sizeof(int) * size);
     // Now a is an array of N ints.
     return 0;
    I am pretty sure this can be done with C++ arrays however, check their forum.
    Callou collei we'll code the way
    Of prime numbers and pings!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to limit user input to a certain number of digits?
    By NewbGuy in forum C Programming
    Replies: 7
    Last Post: 05-08-2009, 09:57 PM
  2. can someone help me with these errors please code included
    By geekrockergal in forum C Programming
    Replies: 7
    Last Post: 02-10-2009, 02:20 PM
  3. SSH Hacker Activity!! AAHHH!!
    By Kleid-0 in forum A Brief History of
    Replies: 15
    Last Post: 03-06-2005, 03:53 PM
  4. Nested Structures - User Input
    By shazg2000 in forum C Programming
    Replies: 2
    Last Post: 01-09-2005, 10:53 AM