大家帮我看下这个程序啊,我感觉怪怪滴!
功能:用C语言控制输出*正方形
我的代码如下,虽说能实现功能,但总觉得怪怪的,有没高手指点下。
最好是用指针结合二维数组的方法实现。
#include <stdio.h> int main(void) { int n; int line,row; printf("pls input the * NO: "); scanf("%d",&n); char a[][]; for(line = 0; line < n;line ++) { for(row = 0; row < n;row ++) { if((line == 0)||(line == n-1)||(row == 0)||(row == n-1)) a[line][row] = '*'; else a[line][row] = ' '; printf("%c",a[line][row]); } printf("\n"); } return 0; } #include <stdio.h> int main(void) { int n; int line,row; printf("pls input the * NO: "); scanf("%d",&n); char** a; a = new char* [n]; for (int i = 0; i < n; ++i) { a[i] = new char[n]; } for(line = 0; line < n;line ++) { for(row = 0; row < n;row ++) { if((line == 0)||(line == n-1)||(row == 0)||(row == n-1)) a[line][row] = '*'; else a[line][row] = ' '; printf("%c",a[line][row]); } printf("\n"); } return 0; }
[解决办法]
char a[][];
错在这里,需要正确初始化
==============
对
char a[][];
你这样定义就 必须指定 数组的大小;
第二个 [] 必须指定, 第一个 [] 可以不指定
[解决办法]
#include <stdio.h> int main(void) { int n; int line,row; printf("pls input the * NO: "); scanf("%d",&n); char *a=new char[n*n]; for(line = 0; line < n;line ++) { for(row = 0; row < n;row ++) { if((line == 0)||(line == n-1)||(row == 0)||(row == n-1)) *(a+line*n+row) = '*'; else *(a+line*n+row) = ' '; printf("%c",*(a+line*n+row) ); } printf("\n"); } delete [] a; return 0; }
[解决办法]
#include <stdio.h> #define n 5 int main(void) { int line,row; printf("pls input the * NO: \n"); char a[n][n];// 不能通过scanf();输入n的值 for(line = 0; line < n;line ++) { for(row = 0; row < n;row ++)//这样的if 写法不是很好,你可以a[0][i],和a[i][0]的时候写下就出来了. { if((line == 0)||(line == n-1)||(row == 0)||(row == n-1)) a[line][row] = '*'; else a[line][row] = ' '; printf("%c",a[line][row]); } printf("\n"); } return 0; }
[解决办法]
to 9楼:
楼主的编译器太牛了吧!能通过????
数组定义的时候要指定长度。你想输入一个数,再指定数组大小,是实现不了的。
----------------------------------------
支持c99的编译器都能通过,这就是新标准中的动态数组!