[英]C, printing 2d dynamic allocated array
I have a problem with printing 2d array. 我在打印二维数组时遇到问题。 After allocating memory for matrix and filling it with 0's it cannot be printed.
为矩阵分配内存并用0填充后,将无法打印。 Here is my code.
这是我的代码。 I had done this before and worked well but now I cannot see the problem.
我以前已经做过并且工作良好,但是现在看不到问题了。
int _tmain(int argc, _TCHAR* argv[])
{
int m, n, num;
float **tab1 = NULL;
for (;;)
{
printf("\n1. Nowy budynek");
printf("\n2. Wyswietl moc pobierana w pomieszczeniach");
printf("\n3. Wlacz swiatlo");
printf("\n4. Wylacz swiatlo");
printf("\n0. Exit\n");
scanf_s("%d", &num);
if (num == 1)
{
do{
printf("Podaj liczbe kondygnacji: ");
scanf_s("%d", &m);
} while (m < 0);
do{
printf("Podaj liczbe pomieszczen: ");
scanf_s("%d", &n);
} while (n < 0);
tworzenie(m, n);
}
for (int i = m - 1; i >= 0; i--)
{
for (int j = 0; j < n; j++)
{
printf("%10.2f", tab1[i][j]);
}
printf("\n");
}
if (num == 2)
{
if (tab1 == NULL)
{
printf("\n Brak budynku! Stworz nowy.\n");
}
else
wyswietlanie(tab1, m, n); <- it crashes here.
}
if (num == 3)
{
if (tab1 == NULL)
{
printf("\n Brak budynku! Stworz nowy.\n");
}
else
wlaczanie(tab1, m, n);
}
if (num == 4)
{
if (tab1 == NULL)
{
printf("\n Brak budynku! Stwórz nowy.");
}
//else
//wylaczanie(tab1,m, n);
}
if (num == 0)
{
// exit(tab1,m, n);
}
}
return 0;
} }
Here is creating the table: 这是创建表:
float** tworzenie(int m, int n)
{
float **tab1;
tab1 = (float**)malloc(m * sizeof(float*));
for (int i = 0; i < n; i++)
{
tab1[i] = (float*)malloc(n * sizeof(float));
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
tab1[i][j] = 0;
}
}
return tab1;
}
and here, printing(upside down): 在这里,打印(上下):
void wyswietlanie(float **tab1, int m, int n)
{
for (int i = m - 1; i >= 0; i--)
{
for (int j = 0; j < n; j++)
{
printf("%10.2f", tab1[i][j]);
}
printf("\n");
}
}
This is the main problem 这是主要问题
if (num == 1)
{
do{
printf("Podaj liczbe kondygnacji: ");
scanf_s("%d", &m);
} while (m < 0);
do{
printf("Podaj liczbe pomieszczen: ");
scanf_s("%d", &n);
} while (n < 0);
/* tworzenie(m, n); this is wrong, must be */
tab1 = tworzenie(m, n);
}
Also, 也,
tab1 = (float**)malloc(m * sizeof(float*));
for (int i = 0; i < n; i++)
{
tab1[i] = (float*)malloc(n * sizeof(float));
}
you malloc
ed m
float *
poitners, and iterate through n
, change it to 你
malloc
ED m
float *
poitners,并通过迭代n
,将其更改为
tab1 = (float**)malloc(m * sizeof(float*));
for (int i = 0; i < m; i++)
{
tab1[i] = (float*)malloc(n * sizeof(float));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.