Change the value of a vector in a function

Asked

Viewed 1,796 times

3

How do I do? I’m trying to:

#include <stdio.h>
#include <stdlib.h>
int changeMap(char mp[], int x, int y){
    mp[x-1][y-1] = 'X';
return 0;
}
int main(){
    char map[][1] = "gabriel";
    printf("%c", map[0][0]);
    changeMap(map, 1, 1);
    printf("%c", map[0][0]);
return 0;
}

The wish is that you return:

t
X

But returns:

G:\PROJETOS\C\main.c||In function 'changeMap':|
G:\PROJETOS\C\main.c|4|error: subscripted value is neither array nor pointer nor vector|
G:\PROJETOS\C\main.c||In function 'main':|
G:\PROJETOS\C\main.c|8|error: invalid initializer|
G:\PROJETOS\C\main.c|10|warning: passing argument 1 of 'changeMap' from incompatible pointer type [enabled by default]|
G:\PROJETOS\C\main.c|3|note: expected 'char *' but argument is of type 'char (*)[1]'|
||=== Build failed: 2 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|

1 answer

7


You got some wrong things in that code:

  • You need to initialize the character map before using it;

  • You cannot assign a string to a character;

    char map[][1] = "gabriel";

Code:

#include <stdio.h>
#include <stdlib.h>

#define N 10

int changeMap(char mp[N][N], int x, int y)
{
    mp[x-1][y-1] = 'X';
    return 0;
}
int main()
{        
    char map[N][N];  //inicialização do map de N por N
    map[0][0]= 'T';  //atribuição do 'T' a posição x=0, y=0

    printf("%c", map[0][0]);
    changeMap(map, 1, 1);
    printf("%c", map[0][0]);
    return 0;
}

Upshot:

TX

Functioning in the ideone

  • I thought to modify directly map would have to create a pointer to char, but so it worked.

  • Also has something else, its function returna 0 that is thrown away, it better be void nay ?

  • It depends on @axell13... I just kept the AP code.

  • Got it. Great answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.