CodeSignal问题。我想完成代码 [英] CodeSignal problem. I want to complete the code
问题描述
我有以下问题。函数 printMatrix
例如接收矩阵:
matrix:
[[0,1,1,2],
[0,5,0,0],
[2,0,3,3]]
我必须使用的代码如下:
The code that I must use is the following:
// Definition for arrays:
// typedef struct arr_##name {
// int size;
// type *arr;
// } arr_##name;
//
// arr_##name alloc_arr_##name(int len) {
// arr_##name a = {len, len > 0 ? malloc(sizeof(type) * len) : NULL};
// return a;
// }
//
//
void printMatrix(arr_arr_integer matrix)
{
}
作为提示,他们告诉我可以通过以下方式确定列和行的数量。
As a clue they give me that the number of columns and rows can be determined in the following way.
int columns = matrix.arr->size; //No.columns
int rows = matrix.size; //No.rows
//Or
int columns = matrix.arr[0].size; //No.columns
int rows = matrix.size; //No.rows
我的问题在于如何编写其余代码,以便前面的曲目可以工作?
My question lies in how is the rest of the code written so that the previous tracks can work?
也就是说,要在函数 printMatrix
中起作用
typedef struct arr_arr_integer {
int size;
type *arr;
} arr_arr_integer;
arr_arr_integer alloc_arr_arr_integer(int len) {
arr_arr_integer a = {len, len > 0 ? malloc(sizeof(type) * len) : NULL};
return a;
}
void printMatrix(arr_arr_integer matrix)
{
int columns = matrix.arr->size; //No.columns
int rows = matrix.size; //No.rows
//print matrix?
}
int main(int argc, char const *argv[])
{
//input matrix?
printMatrix(arr_arr_integer matrix)
return 0;
}
我重复一遍。我必须严格使用此代码
int columns = matrix.arr->size; //No.columns
int rows = matrix.size; //No.rows
问题是,当我尝试使用这些音轨时,出现以下编译错误。
The problem is that when I try to use those tracks I get the following compilation error.
error: request for member 'size' in something not a structure or union
推荐答案
函数 alloc_arr_integer
分配一维整数数组。
The function alloc_arr_integer
allocates a 1D array of integers.
如果需要2D数组,则必须多次调用该函数。
If you need a 2D array, you'll have to call the function multiple times.
类似的东西:
arr_integer my2Darray[rows];
// Create the 2D array
for (int i = 0; i < rows; ++i)
{
my2Darray[i] = alloc_arr_integer(columns);
assert(my2Darray[i].arr != NULL);
}
// Initialize the 2D array
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < columns; ++j)
{
my2Darray[i].arr[j] = i * 1000 + j;
}
}
放在一起:
int main(void)
{
int rows = 3;
int columns = 5;
arr_integer my2Darray[rows];
// Create the 2D array
for (int i = 0; i < rows; ++i)
{
my2Darray[i] = alloc_arr_integer(columns);
assert(my2Darray[i].arr != NULL);
}
//Initialize the 2D array
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < columns; ++j)
{
my2Darray[i].arr[j] = (i + 1) * 1000 + j;
}
}
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < columns; ++j)
{
printf("%d ", my2Darray[i].arr[j]);
}
printf("\n");
}
return 0;
}
输出
1000 1001 1002 1003 1004
2000 2001 2002 2003 2004
3000 3001 3002 3003 3004
这篇关于CodeSignal问题。我想完成代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!