Функции в массиве не отображают правильные значения?
Предполагается, что программа отображает 9 чисел, введенных пользователем в виде платы 3 x 3. Однако все, что я получил, - это несколько довольно странных чисел.
С моей функцией disp_arr
что-то не так, но я просто не знаю, в чем там ошибка. Я довольно новичок в функциях и указателях, но я думаю, что это то, как я учусь!
Это вывод, который я получаю при запуске: 2686636 ошибок клонирования
/* File: StudentID_Surname.c - e.g. 1234567_Wilson.c
* This program finds the range between highest and lowest value of a 2-D array */
#include <stdio.h>
#define NROW 3
#define NCOL 3
/* Write a function
void disp_arr(int a[NROW][NCOL]) { ... }
where a[][] is the 2-D array
Print the entire array to the screen. */
disp_arr( int temp );
int main(void)
{
/* declare needed variables or constants, e.g. */
int ar[NROW][NCOL];
int rows, cols;
int temp[9] = {1,2,3,4,5,6,7,8,9}; /* Storing 9 numbers */
/* prompt for the user to enter nine positive integers to be stored into the array */
int index = 0;
printf( "Please enter 9 positive integers :n");
for ( rows = 0 ; rows < 3 ; rows++ )
{
for ( cols = 0 ; cols < 3 ; cols++ )
{
scanf( "%d", &ar[rows][cols] );
/* Store values in the temp[z] = {1 2 3 4 5 6 7 8 9}*/
temp[index] = ar[rows][cols];
index += 1; /* Increase the array in temp[z] */
}
}
/* Call disp_arr to display the 3 x 3 board */
disp_arr( temp );
}/* end main */
disp_arr( int storedValue )
{
int x,y;
for ( x = 0 ; x < 3 ; x++ )
{
for ( y = 0 ; y < 3 ; y++ )
{
printf( "%dt", storedValue );
}
printf("n");
}
}
Я думал о включении счетчиков, таких как storedValue[counter]
, но он возвращает больше Ошибка = /
disp_arr( int storedValue )
{
int x,y;
int counter = 0
for ( x = 0 ; x < 3 ; x++ )
{
for ( y = 0 ; y < 3 ; y++ )
{
printf( "%dt", storedValue[counter] );
counter += 1;
}
printf("n");
}
}
Любая помощь будет признательна.
Заранее спасибо!
Сэм
/* Editted code after haccks and Rohan's advice */
#include <stdio.h>
#define NROW 3
#define NCOL 3
/* Write a function
void disp_arr(int a[NROW][NCOL]) { ... }
where a[][] is the 2-D array
Print the entire array to the screen. */
disp_arr( int temp );
int main(void)
{
/* declare needed variables or constants, e.g. */
int ar[NROW][NCOL];
int rows, cols;
int temp[9] = {1,2,3,4,5,6,7,8,9}; /* Storing 9 numbers */
/* prompt for the user to enter nine positive integers to be stored into the array */
int index = 0;
printf( "Please enter 9 positive integers :n");
for ( rows = 0 ; rows < 3 ; rows++ )
{
for ( cols = 0 ; cols < 3 ; cols++ )
{
scanf( "%d", &ar[rows][cols] );
/* Store values in the temp[z] = {1 2 3 4 5 6 7 8 9}*/
temp[index] = ar[rows][cols];
index += 1; /* Increase the array in temp[z] */
}
}
/* Call disp_arr to display the 3 x 3 board */
disp_arr( *temp );
}/* end main */
disp_arr( int storedValue )
{
int x,y;
int counter = 0;
for ( x = 0 ; x < 3 ; x++ )
{
for ( y = 0 ; y < 3 ; y++ )
{
/* How on earth do I include the counter inside without errors??*/
printf( "%dt", storedValue );
counter += 1;
}
printf("n");
}
}
3 ответа:
При передаче
temp
вdisp_array
означает, что вы передаете адрес первого элемента массиваtemp
(как он будет распадаться на указатель в этом случае ) на вашу функцию. Для этого параметр функции должен иметь типint *
.Объявите ваш
disp_array
Какvoid disp_arr( int *temp);
Назовем его
disp_array(temp);
И измените определение функции на
void disp_arr( int *storedValue ) { int i; for ( i = 0 ; i < NROW*NCOL ; i++ ) { printf( "%d\t", storedValue[i] ); printf("\n"); } }
disp_arr()
следует принимать параметрint *
, а неint
.И выведите его, как в Вашей 2-й функции.
printf( "%d\t", storedValue[counter] );
Не имеет прямого отношения к вашей проблеме функции, но я думаю, что вы можете очистить свой основной цикл для некоторых. Поскольку похоже, что вы ничего не делаете со своим AR-массивом, вы можете сделать что-то вроде следующего (дважды проверьте меня на синтаксические ошибки, так как я сейчас не на компиляторе, но идея, надеюсь, будет ясна):
int main(void) { /*declare needed variables or constants, e.g. */ int total = NROW * NCOL; int temp[total]; printf("Please enter %d positive integers :\n", total); for(int i = 0; i < total; i++) { scanf("%d", temp[i]); } // Print the array. disp_arr(temp); }