Thread: 2d Array Problem.

  1. #1
    Registered User
    Join Date
    Mar 2003

    2d Array Problem.

    #include <iostream.h>
    #include <fstream.h>
    int main ()
    	ifstream fin ("");
    	ofstream fout ("gift1.out");
    	int NP;
    	fin >> NP;
    	char strName[NP][15];
    	int i;
    	for (i = 0; i< NP;i++)
    	return 0;
    Basically, what this program is supposed to do is input NP names, of length 1 to 14 from a text file. However, when I run the program, I get 3 errors on the line 'char strName[NP][15];' They are:
    error C2057: expected constant expression
    error C2466: cannot allocate an array of constant size 0
    error C2133: 'strName' : unknown size

    Thanks in advance for any help

    {EDIT: The number input for NP is 5}

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    an arrays size must be known at compile time. thats why its saying constant expected.
    To do what you want at runtime you need to use dynamic memory allocation throgh the new/delete operators.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :-

  3. #3
    The Pantless Man CheesyMoo's Avatar
    Join Date
    Jan 2003
    Here is an example of dynamic memory allocation using pointers:
    int main()
        int NP;
        int *point;
        // Allocation memory
       point = new int[NP][15];
       // End of program
       delete point;
       return 0;
    I hope I used proper syntax I'm tired.
    If you ever need a hug, just ask.

  4. #4
    Registered User sikamikaniko's Avatar
    Join Date
    Mar 2003

    The problem is:

    You shoud declare the size of the array.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. 8 Queens, problem with searching 2D array
    By Sentral in forum C++ Programming
    Replies: 35
    Last Post: 03-11-2009, 04:12 PM
  2. Problem with a 2D array.
    By earth_angel in forum C++ Programming
    Replies: 4
    Last Post: 08-20-2005, 11:28 AM
  3. Copying from one 2d array to another....with a twist
    By Zildjian in forum C++ Programming
    Replies: 2
    Last Post: 10-24-2004, 07:39 PM
  4. 2d array problem with vc++
    By LiLgirL in forum C++ Programming
    Replies: 10
    Last Post: 03-16-2004, 08:17 PM
  5. 2d array problem
    By LiLgirL in forum Windows Programming
    Replies: 1
    Last Post: 03-15-2004, 02:23 PM