Home > Software engineering >  How do i use a dynamic array with char type
How do i use a dynamic array with char type

Time:02-18

So try to write a program that allows the user to range the number of rows in the program. I was unable to figure out how I was able to do so using a char array. I know the code works when I do a static array it's just trying to figure out how I can change it dynamically. Im still new to c to please explain in beginner terms.

#include <iostream>
using namespace std;

const int ROW = 7;
const int COL = 4;

void printArray(char s[][COL], int rowsize);
void pickSeat(char s[][COL], int rowsize, int numberofseats);






int main()
{
    int index = 0;

    int size;

    cout << "How many row do you wany:"<<endl;
    cin >> size;

    int row = 1;
    int seats = 28;
    char *arr;
    arr = new char[size][4];

     arr[7][4] =
    {
        {'A', 'B', 'C', 'D' },
        {'A', 'B', 'C', 'D' },
        {'A', 'B', 'C', 'D' },
        {'A', 'B', 'C', 'D' },
        {'A', 'B', 'C', 'D' },
        {'A', 'B', 'C', 'D' },
        {'A', 'B', 'C', 'D' }
    };

    char choice = 'y';

    while (tolower(choice) != 'n' && seats >= 0)
    {
        printArray(arr, row);
        pickSeat(arr, row, seats);

        printArray(arr, COL);
        cout << "Do want to ext? Enter anything to cotiune.(enter n to exit)";
        cin >> choice;



        seats--;
    }
    return 0;
}


void pickSeat(char s[][COL], int rowsize, int numberofseats)
{
    int r1, r2;


    cout << "Pick a seat enter row the colum.";
    cin >> r1;
    cin >> r2;

    if (s[r1 - 1][r2 - 1] == 'x')
    {
        cout << "this seat is taken" << endl;
        numberofseats  ;

        pickSeat(s, rowsize, numberofseats);
    }
    else
    {
        s[r1 - 1][r2 - 1] = 'x';

    }

}

void printArray(char s[][COL], int rowsize) {

    for (int i = 0; i < 7; i  )
    {
        cout << rowsize << " ";

        for (int j = 0; j < 4; j  )
        {
            cout << s[i][j];
            /*if (j == 1)
            {*/
                
          /*  }*/
        }
        cout << endl;
        rowsize  ;

    }
    rowsize = 1;
}

CodePudding user response:

Yo can use better std::vector or if you want array, there is std::array(C 11). Better than array

CodePudding user response:

You show a great deal of confusion in your declaration(s) of arr and your attempt to allocate the shadowed version of arr, e.g.

    char *arr;
    arr = new char[size][4];

     arr[7][4] =
    {
        {'A', 'B', 'C', 'D' },
        {'A', 'B', 'C', 'D' },
        {'A', 'B', 'C', 'D' },
        {'A', 'B', 'C', 'D' },
        {'A', 'B', 'C', 'D' },
        {'A', 'B', 'C', 'D' },
        {'A', 'B', 'C', 'D' }
    };

In the snipped above, you attempt to allocate for the pointer char *arr; an array of size rows and 4 columns. You then turn around and declare arr[7][4] = (or you access 1-past the last row and column) attempting to initialize the array.

You either allocate storage dynamically with new or you declare and initialize the array with automatic storage duration. Not both. (I actually think the confusion stems from your belief you could block-initialize arr after creating storage with new -- you can't)

Instead, just declare and initialize the array with automatic storage duration, e.g.

  int seats = ROW * COL;
  char arr[ROW][COL] = {
      {'A', 'B', 'C', 'D' },
      {'A', 'B', 'C', 'D' },
      {'A', 'B', 'C', 'D' },
      {'A', 'B', 'C', 'D' },
      {'A', 'B', 'C', 'D' },
      {'A', 'B', 'C', 'D' },
      {'A', 'B', 'C', 'D' }
  };

Note: you have already declared:

const int ROW = 7;
const int COL = 4;

So don't use MagicNumbers 4 and 7 later in your code. Instead, use the constants you declared.

If you want a 7x4 array, then there is no need to worry about your size variable or dynamically allocating with new.

Adjust the Number of Seats that Remain in pickSeat()

The only time you change the seats available is in pickSeat(). Shis being C , you can simply pass a reference to seats and update the value in pickSeat(), e.g.

void pickSeat(char s[][COL], int& numberofseats)
{
  int r1, r2;

  for (;;) {  /* loop continually until no seats or 'n' entered */
    std::cout << "\nPick a seat, enter row & colum: ";
    std::cin >> r1;
    std::cin >> r2;
    
    if (std::cin.fail()) {
      std::cerr << " error: invalid int for r1 or r2.\n";
      std::cin.clear();
      std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
      continue;
    }
    
    if (r1 < 0 || ROW   1 <= r1) {
      std::cerr << "error: r1 out of range, must be 0->" << ROW << ".\n";
      continue;
    }
    
    if (r2 < 0 || COL   1 <= r2) {
      std::cerr << "error: r2 out of range, must be 0->" << COL << ".\n";
      continue;
    }
    
    if (s[r1 - 1][r2 - 1] == 'x') {
      std::cout << "  this seat is taken.\n";
    }
    else {
      s[r1 - 1][r2 - 1] = 'x';
      numberofseats--;
      break;
    }
  }
}

The only time you reduce the number of seats available is when the requested seat is available to be assigned. If the seat is already assigned, you simply loop again and give the user a chance to pick a seat not already taken.

As with all input routines, you are better served by looping continually until the user provides valid input, and if not, handle the error, clear any error flag on the stream, remove any extraneous characters left in the input stream with std::cin.ignore().

Pass only your array to printArray()

You defined ROW and COL and those values are available globally. So all you need to pass to your printArray() function is the array itself. You already know the number of ROW and COL, e.g.

void printArray(char s[][COL]) {

  for (int i = 0; i < ROW; i  ) {
    std::cout << i   1 << " ";

    for (int j = 0; j < COL; j  ) {
      std::cout << s[i][j];
    }
    std::cout.put('\n');
  }
}

A complete example with the cleanups discussed above as well as additional validation in pickSeat() could be:

#include <iostream>
#include <limits>

const int ROW = 7;
const int COL = 4;

void printArray (char (*s)[COL]);
void pickSeat (char (*s)[COL], int& numberofseats);

int main()
{
  /*
  int size;

  std::cout << "How many row do you want: ";
  if (!(std::cin >> size)) {
    std::cerr << "invalid integer value.\n";
    return 1;
  }
  */

  int seats = ROW * COL;
  char arr[ROW][COL] = {
      {'A', 'B', 'C', 'D' },
      {'A', 'B', 'C', 'D' },
      {'A', 'B', 'C', 'D' },
      {'A', 'B', 'C', 'D' },
      {'A', 'B', 'C', 'D' },
      {'A', 'B', 'C', 'D' },
      {'A', 'B', 'C', 'D' }
  };
  
  char choice = 'y';

  while (std::tolower(choice) != 'n' && seats >= 0) {
    printArray (arr);
    pickSeat(arr, seats);

    printArray(arr);
    std::cout << "\n[" << seats << "] remain\n" << 
                "Enter anything to cotiune. (n to exit) ";
    std::cin >> choice;
  }
  
  std::cout << "\n[" << seats << "] seats remain unfilled:\n";
  printArray(arr);
}


void pickSeat(char s[][COL], int& numberofseats)
{
  int r1, r2;

  for (;;) {  /* loop continually until no seats or 'n' entered */
    std::cout << "\nPick a seat, enter row & colum: ";
    std::cin >> r1;
    std::cin >> r2;
    
    if (std::cin.fail()) {
      std::cerr << " error: invalid int for r1 or r2.\n";
      std::cin.clear();
      std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
      continue;
    }
    
    if (r1 < 0 || ROW   1 <= r1) {
      std::cerr << "error: r1 out of range, must be 0->" << ROW << ".\n";
      continue;
    }
    
    if (r2 < 0 || COL   1 <= r2) {
      std::cerr << "error: r2 out of range, must be 0->" << COL << ".\n";
      continue;
    }
    
    if (s[r1 - 1][r2 - 1] == 'x') {
      std::cout << "  this seat is taken.\n";
    }
    else {
      s[r1 - 1][r2 - 1] = 'x';
      numberofseats--;
      break;
    }
  }
}

void printArray(char s[][COL]) {

  for (int i = 0; i < ROW; i  ) {
    std::cout << i   1 << " ";

    for (int j = 0; j < COL; j  ) {
      std::cout << s[i][j];
    }
    std::cout.put('\n');
  }
}

(note: your use of size was left commented out in case you did intend to use new in some other manner)

Example Use/Output

Running the code produces what appears to be the wanted behavior, e.g.

$ ./bin/char_array
1 ABCD
2 ABCD
3 ABCD
4 ABCD
5 ABCD
6 ABCD
7 ABCD

Pick a seat, enter row & colum: 4 2
1 ABCD
2 ABCD
3 ABCD
4 AxCD
5 ABCD
6 ABCD
7 ABCD

[27] remain
Enter anything to cotiune. (n to exit) y
1 ABCD
2 ABCD
3 ABCD
4 AxCD
5 ABCD
6 ABCD
7 ABCD

Pick a seat, enter row & colum: 4 3
1 ABCD
2 ABCD
3 ABCD
4 AxxD
5 ABCD
6 ABCD
7 ABCD

[26] remain
Enter anything to cotiune. (n to exit) y
1 ABCD
2 ABCD
3 ABCD
4 AxxD
5 ABCD
6 ABCD
7 ABCD

Pick a seat, enter row & colum: 2 1
1 ABCD
2 xBCD
3 ABCD
4 AxxD
5 ABCD
6 ABCD
7 ABCD

[25] remain
Enter anything to cotiune. (n to exit) y
1 ABCD
2 xBCD
3 ABCD
4 AxxD
5 ABCD
6 ABCD
7 ABCD

Pick a seat, enter row & colum: 2 4
1 ABCD
2 xBCx
3 ABCD
4 AxxD
5 ABCD
6 ABCD
7 ABCD

[24] remain
Enter anything to cotiune. (n to exit) n

[24] seats remain unfilled:
1 ABCD
2 xBCx
3 ABCD
4 AxxD
5 ABCD
6 ABCD
7 ABCD

An additional output of the array is printed at the end to show the final state of selected seats and the number of seats that remain unfilled.

Look things over. This looked to be the direction you were heading in, but there were some choices that could have been made one way or the other. Let me know if I misjudged your intent or if you need further help. There are many additional cleanups that can be implemented, this just reflects those where it was apparent you were a bit confused.

  •  Tags:  
  • c
  • Related