Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to make it possible to read and store 100 char 2D arrays [ 500 ] [ 500 ] in ordered manner?

Tags:

c++

arrays

struct

I have a programming homework which requires storing up to 100 char 2D arrays of size up to 500 * 500, together with 4 numbers associated with each of the array. It should be something like that:

struct BLOCK {
    short x1;
    short y1;
    short x2;
    short y2;
    char points [ 500 ] [ 500 ]; 
    };

The program must read an imput like that:

p
identifier_1 x1 y1 x2 y2
...
identifier_p x1 y1 x2 y2

where

  • p - how many BLOCKs will be declared (range 1 - 100)
  • identifier - identifier of BLOCK (range 1 - 10 000)
  • x1 y1 x2 y2 - unimportant in this context. Point is that the 2D array that they describe can be up to 500 * 500.

My attempt to make it work fails, when I try to enter p > 9 :

#include <iostream>
#include <string>

using namespace std;

struct BLOCK {
    short x1;
    short y1;
    short x2;
    short y2;
    char points [ 500 ] [ 500 ]; 
    };

int main () {

    short numberOfBlocks;

    cin >> numberOfBlocks;

    short indices [ numberOfBlocks ];

    BLOCK BLOCKsTable [ numberOfBlocks ];

}

I also noticed, that this thing doesn't work:

char array [ 100 ] [ 500 ] [ 500 ];

I CAN ONLY USE:

  • iostream
  • string

I CANNOT USE

  • malloc, calloc, alloc etc.
  • std::vector

My question:

  • How to make this thing work? How to be able to declare up to 100 structs BLOCK?
  • Are there other simple ways to achive this goal of declaring and storing 100 2d arrays 500*500?
like image 623
ltw Avatar asked Oct 18 '22 19:10

ltw


1 Answers

500 * 500 = 250000. In round numbers, each instance of BLOCK is going to take up about 250kb.

Your sample code uses a gcc extension to instantiate an array of up to n instances of BLOCK on the stack. Ten instances would therefore take up about 2.5 megabytes. I wouldn't expect that to be a problem, but perhaps your lab's Linux machines are configured with a small maximum on the size of each process's stack. In any case, 100 instances of BLOCK would be expected to take up 20.5 megabytes on the stack, which is far more likely to use up each process's stack allotment, so this wouldn't work in any case.

The answer to the question "How to be able to declare up to 100 structs BLOCK?" is to simply declare them in the global static namespace, instead of on a stack. Your assignment's conditions are very cagey, they appear to be intended to force you to understand the differences between the various types of instantiated objects -- heap, stack, and static/global.

like image 139
Sam Varshavchik Avatar answered Oct 21 '22 16:10

Sam Varshavchik