Magic Squares

19 views
Skip to first unread message

Corey White

unread,
Jan 9, 2023, 12:53:29 PMJan 9
to
This code works fine on linux, but MS Visual Studio
won't compile it because it doesn't dynamically assign
the arrays. When I try to assign them dynamically I get
segmentation faults. Could any of you geniuses help
me out?

// Built off of https://github.com/pdrsa/magicSquares

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 100
using namespace std;

int print_image()
{
// Prints image.txt as ascii banner

FILE *fptr2 = NULL;

if ((fptr2 = fopen("image.txt", "r")) == NULL)
{
fprintf(stderr, "error opening %s\n", "image.txt");
return 1;
}

char read_string[75];

while (fgets(read_string, sizeof(read_string), fptr2) != NULL)
printf("%s", read_string);
fclose(fptr2);

return 0;

}

int start(int n)
{
int num = 0;
int i = 0;
int j = 0;
printf("\n");
int qMagico[n][n];

//----------------------------Part for N in form 2n+1-----------------------------
if (n % 2 == 1)
{
//Resetting the matrix. So where you have 0 is where the matrix hasn't changed yet
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
qMagico[i][j] = 0;
}
}

//This is the position that number 1 will be
i = n / 2;
j = n - 1;

//Loop to determine the position of the numbers
for (num = 1; num <= n * n;)
{
//Treatment so that positions larger than n² works.
i = i % n;
j = j % n;
//Treatment for negative positions to work.
if (i < 0)
{
i = i + n;
}

if (j < 0)
{
j = j + n;
}

//If the position is empty, put NUM in the position above and to the right of the predecessor.
if (qMagico[i][j] == 0)
{
qMagico[i][j] = num;
i--;
j++;
num++;
}

//If the position is occupied, we try to place NUM on the left side of its predecessor.
else
{
j -= 2;
i++;
}
}
}

//----------------------------Part for N in 4n form-----------------------------
else if (n % 4 == 0)
{
// We fill in the square counting from 1 to n²
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
qMagico[i][j] = (n *i) + j + 1;
}

// Changing the values ​​according to the rule
// (n*n+1)-qMagico[i][j]
// Top left corner of the square
for (i = 0; i < n / 4; i++)
{
for (j = 0; j < n / 4; j++)
qMagico[i][j] = (n *n + 1) - qMagico[i][j];
}

// Top right corner of the square
for (i = 0; i < n / 4; i++)
{
for (j = 3 *(n / 4); j < n; j++)
qMagico[i][j] = (n *n + 1) - qMagico[i][j];
}

// Bottom left of the square
for (i = 3 *n / 4; i < n; i++)
{
for (j = 0; j < n / 4; j++)
qMagico[i][j] = (n *n + 1) - qMagico[i][j];
}

// Bottom right of the square
for (i = 3 *n / 4; i < n; i++)
{
for (j = 3 *n / 4; j < n; j++)
qMagico[i][j] = (n *n + 1) - qMagico[i][j];
}

// Now we invert the lines of the 2x2 matrix in the center of the square
for (i = n / 4; i < 3 *n / 4; i++)
{
for (j = n / 4; j < 3 *n / 4; j++)
qMagico[i][j] = (n *n + 1) - qMagico[i][j];
}
}

//----------------------------Part for N in the form 4n + 2-----------------------------
else if (n % 4 == 2)
{
int qMagicoMini[n / 2][n / 2];

//Resetting the matrix. So where you have 0 is where the matrix hasn't changed yet
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
qMagicoMini[i][j] = 0;
}
}

//This is the position that number 1 will be
i = n / 4;
j = (n / 2) - 1;

//Loop to determine the position of the numbers
for (num = 1; num <= ((n / 2)) *((n / 2));)
{
//Treatment so that positions larger than n² work.
i = i % (n / 2);
j = j % (n / 2);
//Treatment for negative positions to work.
if (i < 0)
{
i = i + (n / 2);
}

if (j < 0)
{
j = j + (n / 2);
}

//If the position is empty, put NUM in the position above and to the right of the predecessor.
if (qMagicoMini[i][j] == 0)
{
qMagicoMini[i][j] = num;
i--;
j++;
num++;
}

//If the position is occupied, we try to place NUM on the left side of its predecessor.
else
{
j -= 2;
i++;
}
}

//Now we are going to make some changes to the mini square

//First let's rotate it 90º clockwise
for (int x = 0; x < (n / 4); x++)
{
// Consider elements in group of 4 in
// current square
for (int y = x; y < (n / 2) - x - 1; y++)
{
// Keeping current value in temporary variable
int aux = qMagicoMini[x][y];

// Right Up
qMagicoMini[x][y] = qMagicoMini[y][(n / 2) - 1 - x];

// Down to Right
qMagicoMini[y][(n / 2) - 1 - x] = qMagicoMini[(n / 2) - 1 - x][(n / 2) - 1 - y];

// Left Down
qMagicoMini[(n / 2) - 1 - x][(n / 2) - 1 - y] = qMagicoMini[(n / 2) - 1 - y][x];

// Left
qMagicoMini[(n / 2) - 1 - y][x] = aux;
}
}

//Then we will mirror it on the vertical axis
for (int i = 0; i < (n / 2); i++)
{
for (int j = 0; j < (n / 4); j++)
{
//Saving in auxiliary
int aux = qMagicoMini[i][j];
//Changing positions with the opposite column
qMagicoMini[i][j] = qMagicoMini[i][(n / 2) - j - 1];
//Placing the current position in the opposite column
qMagicoMini[i][(n / 2) - j - 1] = aux;
}
}

//Now we will fill the Square with variations of our Mini Square
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i < n / 2 && j < n / 2)
qMagico[i][j] = qMagicoMini[i][j];
if (i >= n / 2 && j < n / 2)
qMagico[i][j] = qMagicoMini[i - (n / 2)][j] + (3 *n *n / 4);
if (i < n / 2 && j >= n / 2)
qMagico[i][j] = qMagicoMini[i][j - (n / 2)] + (n *n / 2);
if (i >= n / 2 && j >= n / 2)
qMagico[i][j] = qMagicoMini[i - (n / 2)][j - (n / 2)] + (n *n / 4);
}
}

//We will make some changes so that the square becomes magical, first switching between quadrant 2 and 3 (Imagine the quadrants of the square with those of the Cartesian plane)
//WikiHow's Solving a Singly Even Magic Square article is highly recommended to understand the trade-off below.
int temp = n / 4;

for (int i = 0; i < n / 2; i++)
{
for (int j = 0; j < n / 4; j++)
{
if (i == (temp) && j == 0)
{
int aux = qMagico[i][j + (temp)];
qMagico[i][j + (temp)] = qMagico[i + (n / 2)][j + (temp)];
qMagico[i + (n / 2)][j + (temp)] = aux;
}
else
{
int aux = qMagico[i][j];
qMagico[i][j] = qMagico[i + (n / 2)][j];
qMagico[i + (n / 2)][j] = aux;
}
}
}

//If the number is greater than 6 we have to make more exchanges
if (n > 6)
{
for (int i = 0; i < n / 2; i++)
{
for (int j = 0; j < temp - 1; j++)
{
int aux = qMagico[i][n - j - 1];
qMagico[i][n - j - 1] = qMagico[i + (n / 2)][n - j - 1];
qMagico[i + (n / 2)][n - j - 1] = aux;
}
}
}
}

FILE *fp = fopen("matrix.txt", "a");
int total = 0;
int rows = 0;
for (i = 0; i < n; i++)
{
rows = 0;
for (j = 0; j < n; j++)
{
rows = rows + qMagico[i][j];
if (n < 4)
{
if (qMagico[i][j] < 10)
{
printf("%d ", qMagico[i][j]);
fprintf(fp, "%d ", qMagico[i][j]);
}
}
else if (n < 10)
{
if (qMagico[i][j] < 10)
{
printf("0%d ", qMagico[i][j]);
fprintf(fp, "0%d ", qMagico[i][j]);
}
else if (qMagico[i][j] >= 10 && qMagico[i][j] < 100)
{
printf("%d ", qMagico[i][j]);
fprintf(fp, "%d ", qMagico[i][j]);
}
}
else if (n < 32)
{
if (qMagico[i][j] < 10)
{
printf("00%d ", qMagico[i][j]);
fprintf(fp, "00%d ", qMagico[i][j]);
}
else if (qMagico[i][j] >= 10 && qMagico[i][j] < 100)
{
printf("0%d ", qMagico[i][j]);
fprintf(fp, "0%d ", qMagico[i][j]);
}
else if (qMagico[i][j] >= 100 && qMagico[i][j] < 1000)
{
printf("%d ", qMagico[i][j]);
fprintf(fp, "%d ", qMagico[i][j]);
}
}
else if (n < 100)
{
if (qMagico[i][j] < 10)
{
printf("000%d ", qMagico[i][j]);
fprintf(fp, "000%d ", qMagico[i][j]);
}
else if (qMagico[i][j] >= 10 && qMagico[i][j] < 100)
{
printf("00%d ", qMagico[i][j]);
fprintf(fp, "00%d ", qMagico[i][j]);
}
else if (qMagico[i][j] >= 100 && qMagico[i][j] < 1000)
{
printf("0%d ", qMagico[i][j]);
fprintf(fp, "0%d ", qMagico[i][j]);
}
else if (qMagico[i][j] >= 1000 && qMagico[i][j] < 10000)
{
printf("%d ", qMagico[i][j]);
fprintf(fp, "%d ", qMagico[i][j]);
}
}

total = total + qMagico[i][j];
}

fprintf(fp, "\n");
printf("\n");
}

time_t now;
time(&now);
fprintf(fp, "\n%s", ctime(&now));

fprintf(fp, "Rows Total = %d\n", rows);
fprintf(fp, "Matrix Sum = %d\n", total);

printf("\nRows Total = %d\n", rows);
printf("Matrix Sum = %d\n", total);
fclose(fp);

return 0;

}

int main(int argc, char **argv)
{
int step = 0;
while (1)
{
int n;
printf("\n");
if (argc == 2 && step == 0)
{
n = atoi(argv[1]);
}
else
{
printf("Matrix Size: ");
scanf("%d", &n);
}

int cnt = 0;
printf("\n");
step = 0;
while (step == 0)
{
system("cls");
cnt++;

print_image();

time_t now;
time(&now);
printf("%s", ctime(&now));
printf("Saving to matrix.txt\n");

start(n);

FILE *fp = fopen("matrix.txt", "a");
//fprintf(fp, "%s \n", ctime(&now));
printf("Matrix: %d x %d \n", n, n);
fprintf(fp, "Matrix: %d x %d \n", n, n);
fprintf(fp, "Iteration = %d\n\n", cnt);
printf("Iteration = %d\n\n", cnt);
printf("(R) Resets the Matrix.\n");
printf("(Q) Exits.\n");
fclose(fp);

char ch = getc(stdin);
if (ch == 'q' || ch == 'Q')
{
return 0;
}

if (ch == 'r' || ch == 'R')
{
step = 1;
}
}
}

return 0;
}

Barry Schwarz

unread,
Jan 9, 2023, 1:32:08 PMJan 9
to
On Mon, 9 Jan 2023 09:53:20 -0800 (PST), Corey White
<adven...@gmail.com> wrote:

>This code works fine on linux, but MS Visual Studio
>won't compile it because it doesn't dynamically assign
>the arrays. When I try to assign them dynamically I get
>segmentation faults. Could any of you geniuses help
>me out?
>
>int start(int n)
>{
> int num = 0;
> int i = 0;
> int j = 0;
> printf("\n");
> int qMagico[n][n];

It would seem the simplest solution is to replace this definition of
qMagico with

int** qMagico;
qMagico = new int*[n];
for (int ii = 0; ii < n; ii++)
qMagico[ii] = new int[n];

You would need to make a similar adjustment for qMagicoMini

--
Remove del for email

Paavo Helde

unread,
Jan 9, 2023, 1:39:02 PMJan 9
to
09.01.2023 19:53 Corey White kirjutas:
> This code works fine on linux, but MS Visual Studio
> won't compile it because it doesn't dynamically assign
> the arrays. When I try to assign them dynamically I get
> segmentation faults. Could any of you geniuses help
> me out?

>
> int start(int n)
> {
> int qMagico[n][n];

C++ does not have dynamic length arrays, unlike C. Some compilers allow
them as an extension, but MSVC++ is not one of them.

In C++, use e.g.

std::vector<std::vector<int>> qMagico(n, std::vector<int>(n));


Manu Raju

unread,
Jan 9, 2023, 1:55:44 PMJan 9
to
On 09/01/2023 17:53, Corey White wrote:
> This code works fine on linux, but MS Visual Studio
> won't compile it because it doesn't dynamically assign
> the arrays. When I try to assign them dynamically I get
> segmentation faults. Could any of you geniuses help
> me out?
>
>

Try changing "n" TO "N" in two places: (in standard C you need to know
the size of arrays at compile time)

Line 11  and Line 115

I took the original code from github (your link) and compiled in VS 2022
(Microsoft (R) C/C++ Optimizing Compiler Version 19.34.31937 for x64)

<***************************************************************************************************>
#include <stdio.h>
#define N 100

int main()
{

int n, num, i, j;

scanf("%d", &n);

int qMagico[N][N];

//----------------------------Parte para N na forma 2n+1-----------------------------
if (n % 2 == 1 )
{
//Zerando a matriz. Dessa forma onde tiver 0 é onde a matriz não foi alterada ainda
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
qMagico[i][j] = 0;
}
}

//Essa é a posição que o número 1 irá ficar
i = n/2;
j = n-1;

//Laço para ir determinando a posição dos números
for (num = 1; num <= n*n;)
{
//Tratamento para que posições maiores que n² funcionem.
i = i % n;
j = j % n;
//Tratamento para que posições negativas funcionem.
if (i < 0)
{
i = i + n;
}

if (j < 0)
{
j = j + n;
}

//Caso a posicao esteja vazia colocamos NUM na posição acima e a direita do antecessor.
if (qMagico[i][j] == 0)
{
qMagico[i][j] = num;
i--;
j++;
num++;
}
//Caso a posição esteja ocupada tentamos colocar NUM ao lado esquerdo de seu antecessor.
else
{
j-=2;
i++;
}
}
}


//----------------------------Parte para N na forma 4n-----------------------------
else if (n % 4 == 0)
{
// Preenchemos o quadrado contando de 1 até n²
for ( i = 0; i<n; i++)
{
for (j = 0; j<n; j++)
qMagico[i][j] = (n*i) + j + 1;
}

// Mudando os valores de acordo com a regra
// (n*n+1)-qMagico[i][j]
// Canto superior esquerdo do quadrado
for ( i = 0; i<n/4; i++)
{
for ( j = 0; j<n/4; j++)
qMagico[i][j] = (n*n + 1) - qMagico[i][j];
}

// Canto superior direito do quadrado
for ( i = 0; i< n/4; i++)
{
for ( j = 3* (n/4); j<n; j++)
qMagico[i][j] = (n*n + 1) - qMagico[i][j];
}

// Inferior esquerdo do quadrado
for ( i = 3 * n/4; i<n; i++)
{
for ( j = 0; j<n/4; j++)
qMagico[i][j] = (n*n + 1) - qMagico[i][j];
}

// Inferior direito do quadrado
for ( i = 3 * n/4; i<n; i++)
{
for ( j = 3* n/4; j<n; j++)
qMagico[i][j] = (n*n + 1) - qMagico[i][j];
}

// Agora invertemos as linhas da matriz 2x2 no centro do quadrado
for ( i = n/4; i<3* n/4; i++)
{
for ( j = n/4; j<3* n/4; j++)
qMagico[i][j] = (n*n + 1) - qMagico[i][j];
}
}

//----------------------------Parte para N na forma 4n + 2-----------------------------
else if (n%4 == 2)
{
int qMagicoMini[N/2][N/2];

//Zerando a matriz. Dessa forma onde tiver 0 é onde a matriz não foi alterada ainda
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
qMagicoMini[i][j] = 0;
}
}

//Essa é a posição que o número 1 irá ficar
i = n/4;
j = (n/2)-1;

//Laço para ir determinando a posição dos números
for (num = 1; num <= ((n/2))*((n/2));)
{
//Tratamento para que posições maiores que n² funcionem.
i = i % (n/2);
j = j % (n/2);
//Tratamento para que posições negativas funcionem.
if (i < 0)
{
i = i + (n/2);
}

if (j < 0)
{
j = j + (n/2);
}

//Caso a posicao esteja vazia colocamos NUM na posição acima e a direita do antecessor.
if (qMagicoMini[i][j] == 0)
{
qMagicoMini[i][j] = num;
i--;
j++;
num++;
}
//Caso a posição esteja ocupada tentamos colocar NUM ao lado esquerdo de seu antecessor.
else
{
j-=2;
i++;
}
}

//Agora iremos fazer algumas alterações no mini quadrado

//Primeiro vamos rodar ele 90º no sentido horário
for (int x = 0; x < (n / 4); x++)
{
// Consider elements in group of 4 in
// current square
for (int y = x; y < (n/2)-x-1; y++)
{
// Guardando valor atual em variável temporária
int aux = qMagicoMini[x][y];

// Direita pra Cima
qMagicoMini[x][y] = qMagicoMini[y][(n/2)-1-x];

// Baixo pra Direita
qMagicoMini[y][(n/2)-1-x] = qMagicoMini[(n/2)-1-x][(n/2)-1-y];

// Esquerda pra Baixo
qMagicoMini[(n/2)-1-x][(n/2)-1-y] = qMagicoMini[(n/2)-1-y][x];

// Esquerda
qMagicoMini[(n/2)-1-y][x] = aux;
}
}

//Depois vamos espelhar ele no eixo vertical
for (int i = 0; i < (n/2); i++)
{
for (int j = 0; j < (n/4); j++)
{
//Guardando na auxiliar
int aux = qMagicoMini[i][j];
//Trocando de posição pela coluna oposta
qMagicoMini[i][j] = qMagicoMini[i][(n/2)-j-1];
//Colocando a posição atual na coluna oposta
qMagicoMini[i][(n/2)-j-1] = aux;
}
}

//Agora preencheremos o Quadrado com variações de nosso Mini Quadrado
for (int i = 0; i < n; i ++)
{
for (int j = 0; j < n; j++)
{
if (i < n/2 && j < n/2)
qMagico[i][j] = qMagicoMini[i][j];
if (i >= n/2 && j < n/2)
qMagico[i][j] = qMagicoMini[i - (n/2)][j] + (3*n*n/4);
if (i < n/2 && j >= n/2)
qMagico[i][j] = qMagicoMini[i][j - (n/2)] + (n*n/2);
if (i >= n/2 && j >= n/2)
qMagico[i][j] = qMagicoMini[i - (n/2)][j - (n/2)] + (n*n/4);
}
}

//Faremos umas trocas para que o quadrado se torne mágico, primeiramente trocando entre o quadrante 2 e 3 (Imagine os quadrantes do quadrado com os do plano cartesiano)
//É extremamente recomendado o artigo Solving a Singly Even Magic Square do WikiHow para que se entenda a troca a seguir.
int temp = n/4;

for (int i = 0; i < n/2; i++)
{
for (int j = 0; j < n/4; j++)
{
if (i == (temp) && j == 0)
{
int aux = qMagico[i][j+(temp)];
qMagico[i][j+(temp)] = qMagico[i + (n/2)][j+(temp)];
qMagico[i + (n/2)][j+(temp)] = aux;
}
else
{
int aux = qMagico[i][j];
qMagico[i][j] = qMagico[i+(n/2)][j];
qMagico[i+(n/2)][j] = aux;
}
}
}

//Caso o numero seja maior que 6 temos que fazer mais trocas
if(n > 6)
{
for (int i = 0; i < n/2; i++)
{
for (int j = 0; j < temp-1; j++)
{
int aux = qMagico[i][n-j-1];
qMagico[i][n-j-1] = qMagico[i+(n/2)][n-j-1];
qMagico[i + (n/2)][n-j-1] = aux;
}
}
}

}

printf("\n\nn = %d, soma = %d\n\n", n, (((n*n) + 1)*(n/2)));
FILE *fp = fopen("qMagico.txt", "w");

for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", qMagico[i][j]);
fprintf(fp, "%d ", qMagico[i][j]);
}
fprintf(fp, "\n");
printf("\n");
}
fclose(fp);

return 0;

}
<***************************************************************************************************>


Paavo Helde

unread,
Jan 9, 2023, 2:05:17 PMJan 9
to
09.01.2023 20:56 str...@shellcrash.com kirjutas:
> On Mon, 09 Jan 2023 10:31:41 -0800, Barry Schwarz <schw...@delq.com>
> wrote:
>
>> ];
>
> That is similar to what I tried
> But when I do:
>
>
> int** qMagicoMini;
> qMagicoMini = new int*[n / 2];
> for (int cc = 0; cc < n; cc++)
> qMagicoMini[cc] = new int[n / 2];
>
> I get a segmentation fault when I make a magic square of size 6

This is because you assign to nonexistant qMagicoMini[cc] when cc>n/2
(you have only allocated n/2 elements in qMagicoMini0)

Anyway, what's this obsession with error-prone and memory-leaky manual
new? A proper C++ application level program should not contain a single
naked new nowadays. Use std::vector, that's what is there for, and you
get better error diagnostics in Debug builds as an extra bonus.


Keith Thompson

unread,
Jan 9, 2023, 2:12:19 PMJan 9
to
Corey White <adven...@gmail.com> writes:
> This code works fine on linux, but MS Visual Studio
> won't compile it because it doesn't dynamically assign
> the arrays. When I try to assign them dynamically I get
> segmentation faults. Could any of you geniuses help
> me out?
>
> // Built off of https://github.com/pdrsa/magicSquares
>
> #include <stdio.h>
> #include <stdlib.h>
> #include <time.h>
> #define N 100
> using namespace std;
[...]
> int start(int n)
> {
[...]
> int qMagico[n][n];
[...]

The "using namespace std;" indicates that this is C++, not C. The
original code on GitHub is C. Did you add the "using namespace std;"?

Visual Studio can compile C, though it can be a little tricky to get it
to do so. I suggest backing out any C++-specific changes you've made.
Make sure the source file is named with a ".c" extension.

qMagico is a variable-length array (VLA). This is a feature that was
added to C in the 1999 edition of the ISO standard (and made optional in
the 2011 edition). (C++ doesn't have VLAs) I don't think Microsoft's C
or C++ compiler supports VLAs. Apparently it's possible to configure
newer versions of Visual Studio to use clang rather than Microsoft's
compiler; I don't know whether you want to go to that much trouble.

If you want arrays whose size is not fixed at compile time and your
compiler doesn't support VLAs, you can use modify your code to use
malloc to allocate your arrays (and free to deallocate them), or you can
convert the code to C++ and use std::vector.

Recommended reading: Section 6 of the comp.lang.c FAQ <https://www.c-faq.com/>.

--
Keith Thompson (The_Other_Keith) Keith.S.T...@gmail.com
Working, but not speaking, for XCOM Labs
void Void(void) { Void(); } /* The recursive call of the void */

Manu Raju

unread,
Jan 9, 2023, 2:16:40 PMJan 9
to
On 09/01/2023 19:05, Paavo Helde wrote:
>
>
> A proper C++ application level program should not contain a single
> naked new nowadays. Use std::vector, that's what is there for, and you
> get better error diagnostics in Debug builds as an extra bonus.
>
>
The original program isn't a proper C++ Application. It is a C program
posted on C++ Newsgroup.

I could rewrite the entire program in C++ ( or C# using Lists<int>) if I
knew what Majic Squares are supposed to do. I don't know what they do in
the first place.

We can make changes to the original program but do they give the
intended results? I don't know because the squares are Magic!!!!!!


Bonita Montero

unread,
Jan 9, 2023, 2:27:44 PMJan 9
to
Am 09.01.2023 um 19:31 schrieb Barry Schwarz:

> It would seem the simplest solution is to replace this definition of
> qMagico with
>
> int** qMagico;
> qMagico = new int*[n];
> for (int ii = 0; ii < n; ii++)
> qMagico[ii] = new int[n];

Better use a vector of vectors.

Paavo Helde

unread,
Jan 9, 2023, 2:47:19 PMJan 9
to
09.01.2023 21:15 Manu Raju kirjutas:
> On 09/01/2023 19:05, Paavo Helde wrote:
>>
>>
>> A proper C++ application level program should not contain a single
>> naked new nowadays. Use std::vector, that's what is there for, and you
>> get better error diagnostics in Debug builds as an extra bonus.
>>
>>
> The original program isn't a proper C++ Application. It is a C program
> posted on C++ Newsgroup.

It contained a "using namespace", so it was not a proper C program
either. And a naked 'new' is not a C feature anyway. In C one should
need to use malloc() to avoid VLA-s, and malloc() is actually only very
slightly worse than a naked 'new'.

>
> I could rewrite the entire program in C++ ( or C# using Lists<int>) if I
> knew what Majic Squares are supposed to do. I don't know what they do in
> the first place.


No need to rewrite it all at once, one can start from problematic parts.
That's the exact reason why C++ is so backwards-compatible with C, to
allow piecewise changes.

>
> We can make changes to the original program but do they give the
> intended results? I don't know because the squares are Magic!!!!!!
>

I see. It would be so much better with magic balls, not squares!


Scott Lurndal

unread,
Jan 9, 2023, 2:52:47 PMJan 9
to

Keith Thompson

unread,
Jan 9, 2023, 3:04:29 PMJan 9
to
Manu Raju <M...@invalid.invalid> writes:
> On 09/01/2023 17:53, Corey White wrote:
>> This code works fine on linux, but MS Visual Studio
>> won't compile it because it doesn't dynamically assign
>> the arrays. When I try to assign them dynamically I get
>> segmentation faults. Could any of you geniuses help
>> me out?
>
> Try changing "n" TO "N" in two places: (in standard C you need to know
> the size of arrays at compile time)

C99 supports variable-length arrays (VLAs). C11 made them optional.
The original code on GitHub is C, and assumes either a C99 compiler or a
C11+ compiler that supports VLAs.

Microsoft's C compiler apparently does not support VLAs. C++ never
adopted VLAs.

Another option for the OP would be to use a non-Microsoft C compiler for
Windows (probably gcc), for example by installing Cygwin or MinGW-w64.

[...]

Bonita Montero

unread,
Jan 9, 2023, 4:56:04 PMJan 9
to
Am 09.01.2023 um 21:04 schrieb Keith Thompson:

> C99 supports variable-length arrays (VLAs). C11 made them optional.
> The original code on GitHub is C, and assumes either a C99 compiler
> or a C11+ compiler that supports VLAs.
> Microsoft's C compiler apparently does not support VLAs. C++ never
> adopted VLAs.
> Another option for the OP would be to use a non-Microsoft C compiler
> for Windows (probably gcc), for example by installing Cygwin or MinGW
> -w64.

VLAs were dropped from the Linux kernel and Torvalds said that if there
is an upper limit on the size of a VLA you can immediately allocate a
frame with a static size which is the maximum size for your VLA.
I'm using my own class called overflow_array<> that has a constant allo-
cated capacity like a array<> and a variable size. If that size exceeds
the capacity there's a heap-allocation and the stack-"allocated" "array"
remains unused. I think that's the best compromise. As far as I know
boost has also sth. like that.


Sam

unread,
Jan 9, 2023, 8:32:02 PMJan 9
to
Corey White writes:

> This code works fine on linux, but MS Visual Studio
> won't compile it because it doesn't dynamically assign
> the arrays. When I try to assign them dynamically I get
> segmentation faults. Could any of you geniuses help
> me out?

You will find std::vector down the hall, last door on your left.

Reply all
Reply to author
Forward
0 new messages