2014-09-01 1 views
0

행과 열의 수가 고정되어 있으며 콘솔 입력에서 열 값을 가져 오는 2 차원 배열을 만들고 싶습니다.C에서 콘솔 입력 한 줄로 배열을 만드는 방법은 무엇입니까?

void main() { 
    int myArray[3][5]; 
    int i; 
    int a, b, c, d, e; // for taking column values 

    for (i = 0; i < 3; i++) { // i represents number of rows in myArray 
     printf("Enter five integer values: "); 
     // taking 5 integer values from console input 
     scanf("%d %d %d %d %d", &a, &b, &c, &d, &e); 

     // putting values in myArray 
     myArray[i][1] = a; 
     myArray[i][2] = b; 
     myArray[i][3] = c; 
     myArray[i][4] = d; 
     myArray[i][5] = e; 
    } 
    // print array myArray values (this doesn't show the correct output) 
    for (i = 0; i < 3; i++) { 
     printf("%d\t %d\t %d\t %d\t %d\t", &myArray[i][1], &myArray[i][2], 
       &myArray[i][3], &myArray[i][4], &myArray[i][5]); 
     printf("\n"); 
    } 
} 

이 프로그램을 실행하면 올바르게 입력되지만 예상대로 배열 출력이 표시되지 않습니다. 어떻게하면 될까요? 도와주세요.

+2

myArray의 사용을 시도 [I] [1]'- 왜 '및'? 솔루션에 대한 감사합니다. – Mat

답변

2

두 번째 차원은 myArray [i] [0]에서 myArray [i] [4]로 선언됩니다. myArray [i] [1]에서 myArray [i] [5]

1

최종 인쇄물에는 불필요한 & 명의 작업자가있었습니다. 또한 코드를 더 간결하게 만들기 위해 a, b, c, d, e 변수를 제거했습니다. 각 요소의 주소를 직접 전달하는 배열의 값을 scanf 할 수 있습니다.

#include <stdio.h> 
void main() 
{ 
    int myArray[3][5]; 
    int i; 

    for(i=0; i<3; i++){ //i represents number of rows in myArray 
     printf("Enter five integer values: "); 
     //taking 5 integer values from console input 
     scanf("%d %d %d %d %d",&myArray[i][0], &myArray[i][1], &myArray[i][2], &myArray[i][3], &myArray[i][4]); // you can directly scan values in your matrix 

    } 


    for(i=0; i<3; i++){ 
     printf("%d\t %d\t %d\t %d\t %d\t\n", myArray[i][0], myArray[i][1], myArray[i][2], myArray[i][3], myArray[i][4]); // no need for the & sign which returns the address of the variable 
    } 

} 
+0

. 나는 알아야 할 것이 하나 더있다. 2 차원 배열의 행 값이 정수가되고 열 값이 float/double이 될 가능성이 있습니까? 내 배열 행에서 학생의 롤 번호와 열이 여러 자습서 번호를 나타내는 경우 튜토리얼 번호에 대해 롤 및 부동/이중에 정수를 사용할 수 있습니까? – Esika

0

'및 %1d

#include <stdio.h> 

int main(void) 
{ 
    int i; 
    int x[5]; 

    printf("Enter The Numbers: "); 

    for(i = 0; i < 5; i++) 
    { 
     scanf("%1d", &x[i]); 
    } 

    for(i = 0; i < 5; i++) 
    { 
     printf("%d\n", x[i]); 
    } 

    return 0; 
} 
관련 문제