第一个问题:0 个错误,0 个警告。确定代码是正确的。告诉我有什么问题吗?(这是程序的一部分。)我不明白出了什么问题。至少它会显示
array[3][3] = {{1,1,1},{1,1,1},{1,1,1}}
第二个问题:但我看到的不是“零”,而是清晰的字段。(我什么也没看到)但是如果有
{{1,1,1},{1,1,1},{1,1,1}}
,我看到'1's...告诉我为什么?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//#define L 3 /* Including the [0]-element */
//#define C 3 /* Including the [0]-element */
#define RANGE 100 /* Set up the range of random values */
int fill_in(int *, int, int); /* Prototype of function */
int main()
{
int L = 3, C = 3;
int array[L][C]; // L - Line, C - Column
int i, j; // Global variables
int * aPtr;
aPtr = &array[L][C];
srand((unsigned)time(NULL));
fill_in(aPtr, L - 1, C - 1);
/* Displaying array (AFTER) */ // <--- going to make a function, but my first one
printf("\nAFTER:\n"); // doesn't work correctly =(
for (i = 0; i <= L - 1; i++)
{
for (j = 0; j <= C - 1; j++)
printf("%2.d ", array[i][j]);
printf("\n");
}
return 0;
}
int fill_in( int * aptr, int m, int n) /// PROBLEM? O_о
{
int arr[m][n];
int i, j; // Local variables
/* Filling array with random values */
for (i = 0; i <= m - 1; i++)
{
for (j = 0; j <= n - 1; j++)
arr[i][j] = 1; //1 + rand()%RANGE; // If each element == 1, it works!
}
return arr[i][j];
}
更新:我已经解决了!解释在代码的注释中。以下代码正常工作:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define Lines 2 /* Including the [0]-element */
#define Columns 2 /* Including the [0]-element */
#define RANGE 100 /* Set up the range of random values */
int fill_in(int*, int, int); /* Prototypes of functions */
int display(int*, int, int);
int main()
{
int L = Lines, C = Columns;
int array[L][C]; // L - Line, C - Column
int* aPtr;
aPtr = &array[0][0];
srand((unsigned)time(NULL));
fill_in(aPtr, L, C); /* Filling array with random values. */
display(aPtr, L, C); /* Displaying array. */
return 0;
}
////////////////////////////////////////////////////////////////////
/** Eureka! The fact is that pointer of a[0][0] is *ptr[0], and
the pointer of a[2][2] is *ptr[8] ---> The 8-th element of the array[2][2].
>>>> Pointer sees array[][] not as matrix (square), but as a line!
>>>> As if to make a line of a square matrix!
*/
int fill_in(int* aptr, int m, int n) /* Filling array with random values. */
{
int i; // Local variables
int max_number_of_element = ((m+1)*(n+1)-1);
for (i = 0; i <= max_number_of_element; i++)
*(aptr + i) = 1 + rand()%RANGE;
return *aptr;
}
int display(int* aptr, int m, int n) /* Displaying array. */
{
int i;
int count = 1;
int max_number_of_element = ((m+1)*(n+1)-1);
for (i = 0; i <= max_number_of_element; i++)
{
printf("%2.d ", *(aptr + i));
if (count % (n+1) == 0)
printf("\n");
count++;
}
return i;
}
代替:
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
aptr[i * n + j] = 1;
我用过:
for (i = 0; i <= max_number_of_element; i++)
*(aptr + i) = 1;
//Pointer sees array[][] not as matrix (square), but as a direct sequence (line).
不确定它是否在数组之外做任何事情,但主要问题已经解决。
PS如果我错了,请告诉我。