G
G
Gagatyn2017-10-20 01:06:04
C++ / C#
Gagatyn, 2017-10-20 01:06:04

How to assign a char character to an integer element of an array?

I have a 3x3 matrix of type int. How to assign an element to any of this matrix any character? I took the second char array to at least see the result.

// у arrayI значения элементов от 1 до 9
void slct(int arrayI[3][3], char arrayC[3][3]) {
    int x = getchar() - '0';
    memset(arrayC, '-', sizeof arrayC);
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if( x == arrayI[i][j]) {
                arrayC[i][j] = 'W';
            }
            printf("[ %d ]", arrayC[i][j]);
        }
        printf("\n");
    }
}
/* Вывод такой:
Вводим 5 и на 5, т.е. 4 элементе 88, как сделать 'W'?
[ 0 ][ 0 ][ 0 ]
[ 0 ][ 88 ][ 0 ]
[ 0 ][ 0 ][ -115 ] 
Почему 8 элемент равен чему-то? Как это исправить?
*/

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2017-10-20
@jcmvbkbc

memset(arrayC, '-', sizeof arrayC);

Doesn't do what you expect. sizeof arrayC will be equal to the size of the pointer, since the array is passed to the function as a pointer, despite the fact that the prototype says int arrayC[3][3].
You didn't show how the arrayI array is initialized, so it's not known when this condition will work.
Exactly as you do -arrayC[i][j] = 'W';

R
res2001, 2017-10-20
@res2001

In C/C++, the char type is a 1-byte signed integer. Therefore, intu is assigned directly, without any dancing:
arayI[i][j] = arrayC[i][j]
To print a character instead of a number, use the template %c in printf.
It looks like your code doesn't match the output you provide in the comments below.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question