Is it possible to assign the first column of a line of a / a vector / matrix?

1

having as example a vector of two dimensions of type char 2x2:

char vet[2][2];

Is it possible to assign to the first line indices of this vector? or do they work like a pointer to the other rows and columns?

I tried to do it as follows

#include <stdio.h>
#include <string.h>


int main(void){
    char v2[2][2];
    v2[0] = 'a'; // LINHA 10
    v2[1] = 'c'; // LINHA 11
    printf("%c\t%c", v2[0], v2[1]);
    return 0;
}

The compiler is returning me 2 errors on line 10 and 11

  

assignment to expression whit array type

Finally the code does not compile

    
asked by anonymous 07.09.2017 / 22:54

2 answers

1

Assanges, you have to keep in mind that when you are working with arrays you need to pass the full address of the position to which you want to make an assignment. The declaration and use of matrix and vector are different.

char vet[2]; //Isso é um vetor de duas posições
char matriz[2][5]; //Isso é uma matriz com 2 linhas e 5 colunas

Therefore, we can conceptually represent the arrangement of elements in memory as follows:

AfunfactaboutthearraythatwenormallydonothavetoworryaboutinPCprogrammingisthatalthoughthereisthis"theoretical" arrangement of elements in array format, elements are actually arranged in memory spaces sequentially , ie for the example above array [1] [0] in memory comes soon after array [0] [4]

One more fact about arrays is that when you refer to it this way "array [1]" you are pointing to the value of the memory address. You can test with the example below:

#include <stdio.h>
#include <string.h>


int main(void){
    char v2[2][5];
    printf("%d", v2[0]); //Imprimirá um número X
    printf("\n%d\n", v2[1]); //Imprimirá um número X+5, pois a linha 0 tem 5 colunas

    return 0;
}

But finally, to assign a value to an array position you need to pass the position completely. Example:

char matriz[2][3];
matriz[1][2] = 'a';

The result would be:

    
08.09.2017 / 19:21
0

When you start v2[0] or v2[1] , you are not yet referring to a character. To refer to a character, you need the two indexes, such as v2[0][0] , or v2[1][0] .

Type char[2][] needs two indexes to be transformed into char . Only by a single index will you get a reference to a memory region that can not have attribution, so it complains that the assignment to a array can not occur.

By the way, the messages seem to refer to the lines:

v2[0] = 'a';
v2[1] = 'c';

Since the print line has no attribution in it.

    
07.09.2017 / 23:02