Code in C simply date

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

void recebeNumCartas(int *nAlice, int *nBeatriz){

    scanf("%d %d", nAlice, nBeatriz);

}

int achaMenor(int nAlice, int nBeatriz, int menor){

    menor = nAlice;

    if (nBeatriz < nAlice){
        menor = nBeatriz;
    }

    return menor;
}

int realizaTroca(int nAlice, int nBeatriz, int menor){

    int cartasAlice[nAlice];
    int cartasBeatriz[nBeatriz];
    int troca[menor * 2];

    for (int i = 0; i < nAlice; ++i){
        scanf("%d", cartasAlice[i]);
    }

    for (int j = 0; j < nBeatriz; ++j){
        scanf("%d", cartasBeatriz[j]);
    }
}

int main(void){

    int nAlice = 0;
    int nBeatriz = 0;
    int menor = 0;

    recebeNumCartas(&nAlice, &nBeatriz);
    menor = achaMenor(nAlice, nBeatriz, menor);

    realizaTroca(nAlice, nBeatriz, menor);

    getchar();
    getchar();
    return 0;
}

I'm doing an exercise with the above code, but after the first loop of the function is performed, the program runs without any error message. I need some help to understand what's going on.

    
asked by anonymous 16.07.2018 / 13:20

1 answer

4

Your code is returning a segmentation fault in vector reading.

Here is the documentation for the function:

int scanf ( const char * format, ... );
  

Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments.

     

The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier in the format string.

This says that additional function arguments must be pointers (or a memory address) for already allocated objects of the same function type.

So your problem can be solved simply by setting the & operator to scanf as follows:

scanf("%d", &cartasAlice[i]);
scanf("%d", &cartasBeatriz[j]);

At the beginning of the code you were already using your code without & and it worked, in the following statement:

scanf("%d %d", nAlice, nBeatriz);

This occurs because the nAlice and nBeatriz variables already contain memory addresses. Here's the function declaration:

void recebeNumCartas(int *nAlice, int *nBeatriz)

These * indicates that this variable must contain a memory address for an integer variable. This address is being passed in the call, with & in this line:

recebeNumCartas(&nAlice, &nBeatriz);

So scanf is getting exactly what he expects.

    
16.07.2018 / 13:39