我正在尝试解决一项特定任务。为了完成这项任务,我尝试练习到目前为止学到的所有技能。由于我正在处理多维数组,所以我想像往常一样输入它。
这次数组必须可以编辑数组。
typedef char grid[][];
这是我在特殊头文件中尝试的内容。我收到了错误
error: array type has incomplete element type
如果有必要查看更多详细信息,我会发布完整的代码:
main.c
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "functions.h"
#include "tester.h"
#include "magic.h"
int main(int argc, char **argv)
{
int size = getSize();
grid pascal[size][size];
drawGrid(pascal, size);
return EXIT_SUCCESS;
}
functions.c
#include <stdlib.h>
#include <stdio.h>
#include "magic.h"
#include <math.h>
/* C array: Pascal triangle exercise
* By using two-dimensional array, write C program to display
* a table that represents a Pascal triangle of any size.
*
* In Pascal triangle, the first and the second rows are set to 1.
* Each element of the triangle (from the third row downward) is the sum
* of the element directly above it and the element to the left of the
* element directly above it. See the example Pascal triangle(size=5) below:
*
*
* 1
* 1 1
* 1 2 1
* 1 3 3 1
* 1 4 6 4 1
*
*/
int getSize(void)
{
int size;
printf("Please enter the size of the Pascal Triangle:");
scanf("%d",&size);
printf("\n");
size = (int) sqrt(size);
printf("Pascal Triangle will be %d big", (size*size));
return size;
}
void createVoid(grid pascal, int size)
{
int i = 0;
int j = 0;
while(i < size){
while (j < size){
if (j > i){
pascal[i][j] = ' ';
}
j++;
}
i++;
}
}
void createNumbers(grid pascal, int size)
{
int i = 0;
int j = 0;
while(i < size){
while (j < size){
if (j <= i){
if (i == 0){
pascal[i][j] = '1';
}else if (i == j){
pascal[i][j] = '1'
}else{
pascal[i][j] = pascal[i][j-1] - VALUE_ZERO + pascal[i-1][j];
}
}
j++;
}
i++;
}
}
void printGrid(grid pascal)
{
int i = 0;
int j = 0;
while (i < size){
while (j < size){
printf ("%3c", pascal[i][j]);
j++;
}
i++;
}
}
void drawGrid(grid pascal, int size)
{
createVoid(pascal, size);
createNumbers(pascal, size);
printGrid(pascal);
}
functions.h
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
#include "magic.h"
int getSize(void);
void drawGrid(grid pascal, int size);
void createVoid(grid pascal, int size);
void createNumbers(grid pascal, int size);
void printGrid(grid pascal, int size);
#endif // FUNCTIONS_H
magic.h
#ifndef MAGIC_H
#define MAGIC_H
#include <stdlib.h>
#define VALUE_ZERO '0'
typedef char grid[][];
#endif // MAGIC_H
答案 0 :(得分:3)
typedef
声明char grid[][]
是非法的,因为你不能忽略最右边的指示。一般来说(三维及更多维度),您只能省略最左边的一个。
C99标准引入了一种声明和定义具有未知大小的多维数组(称为VLAs 1 )的函数的方法。声明这种功能的正确形式是:
void drawGrid(int, char pascal[*][*]);
或者如果您希望保留参数名称:
void drawGrid(int size, char pascal[size][size]);
后者(也只是后者)也可用于定义。
请注意,typedef
声明不能应用于文件范围内的VLA(即,在任何函数之外)。参考C11(N1570草案),§6.7.8/ 2 类型定义:
如果typedef名称指定了可变修改的类型,那么它应该 有块范围。
1)当然,VLA也可以是一维的,如int n = 100; int a[n] = {0};
。