C++ uses malloc to create dynamic arrays

Doing a queen placement procedure in the last few days.

Subject: A34 . queen placement problem

Analysis: The problem requires that N queens be placed on an N×N chessboard so that they cannot attack each other, that is, any two queens cannot be in the same row, column, or diagonal line, that is, queen N is on the same line. This row, this column, this diagonal line can only appear once.

The complete solution of this example will not be explored this time. When I was doing this problem, I was exploring how to dynamically create an array. Since the problem requires an NXN chessboard, I want to build such a chessboard based on reasonable values ​​input by the user. For example, if I enter 5 , a 5X5 chessboard is created. But everyone who has learned it knows that when defining an array, you cannot use unknown variables to define

That is, it cannot be done as follows

int a; 

cout<<" Please enter a positive integer within 20 "<<endl;

int  NN [a][a] ; 

**************************************************** **************************************************** **************************************************** ******************************** This time we will explore how to dynamically create an array by entering a custom value.

This time, the malloc function is used.

#include<iostream>

#include<cstdlib>

#include<cstring>

using namespace std;

intmain()

{

    int a;

    cout<<"Please enter a positive integer N (N>4) within 20"<<endl;

    cin>>a;

    char **p=NULL;int i;

    p=(char ** )malloc(sizeof(char *)*a);

    for(i=0;i<a;i++)

         p[i]=(char *)malloc(sizeof(char)*a);

            /* free memory */

        for(i=0;i<a;i++)

            free(p[i]);

        free(p);

        for(i=0;i<a+1;i++)

         { for(int j=0;j<a;j++)

         printf("%d\t",p[i][j]);//Directly use the array to access

         printf("\n");

         }

return 0;

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324907456&siteId=291194637