嘿伙计们我试图动态构建array2d但它不起作用并说没有放置我的代码
int i = ZERO;
int j = ZERO;
int lenRow = ZERO;
int rows = ZERO;
printf("Enter number of rows: ");
scanf("%d", &rows);
int** arr = malloc(rows * sizeof(int*));
if (NULL == arr)
{
printf("Unseccess");
return 1;
}
for (i = ZERO; i < rows; i++)
{
printf("Enter array length for row %d: ", i);
scanf("%d", &lenRow);
arr[i] = malloc(lenRow * sizeof(int));
for (j = ONE; j <= lenRow; j++)
{
printf("Enter value for array: ");
scanf("%d", &arr[j]);
if (NULL == arr[j])
{
printf("Unseccess");
return 1;
}
}
}
free(arr);
所以问题是我如何用这种格式打印这个
3 1 5 2 3 1 8
答案 0 :(得分:1)
您的代码应该是
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i = 0;
int j = 0;
int lenRow = 0;
int rows = 0;
printf("Enter number of rows: ");
scanf("%d", &rows);
int** arr = malloc(rows * sizeof(int*));
if (NULL == arr)
{
printf("Unseccess\n");
return 1;
}
for (i = 0; i < rows; i++)
{
printf("Enter array length for row %d: ", i);
scanf("%d", &lenRow);
arr[i] = malloc(lenRow * sizeof(int));
if (arr[i] != NULL)
{
for (j = 0; j < lenRow; j++)
{
printf("Enter value for array: ");
scanf("%d", &arr[i][j]);
}
}
else
{
printf("Unseccess\n");
return 1;
}
}
for (i = 0; i < rows; i++)
free(arr[i]);
free(arr);
}
很多事情:
for (j = 1; j <= lenRow; j++)
----必须是---&gt; for (j = 0; j < lenRow; j++)
scanf("%d", &arr[j]);
必须为scanf("%d", &arr[i][j]);
malloc
返回值修改强>
要打印插入的数据,您必须跟踪每行的所有宽度,例如:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i = 0;
int j = 0;
int lenRow = 0;
int rows = 0;
printf("Enter number of rows: ");
scanf("%d", &rows);
int** arr = malloc(rows * sizeof(int*));
int *widths = malloc(rows * sizeof(int));
if ((NULL == arr) || (widths == NULL))
{
printf("Unseccess\n");
return 1;
}
for (i = 0; i < rows; i++)
{
printf("Enter array length for row %d: ", i);
scanf("%d", &lenRow);
widths[i] = lenRow;
arr[i] = malloc(lenRow * sizeof(int));
if (arr[i] != NULL)
{
for (j = 0; j < lenRow; j++)
{
printf("Enter value for array: ");
scanf("%d", &arr[i][j]);
}
}
else
{
printf("Unseccess\n");
return 1;
}
}
for (i=0; i<rows; i++)
{
for(j=0; j<widths[i]; j++)
{
printf("Matrix[%d][%d] = %d\n", i, j, arr[i][j]);
}
}
for (i = 0; i < rows; i++)
free(arr[i]);
free(arr);
free(widths);
}