Code in C simply closes

Asked

Viewed 48 times

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 am doing an exercise with the above code, but after the first for loop of the performed functionTroca runs the program terminates without any error message. I need help understanding what’s going on.

1 answer

4

Your code is returning one segmentation fault in the vector reading.

Follow the function documentation:

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 Within the format string.

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

So your problem can be solved by simply putting the operator & in the scanf thus:

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

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

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

This occurs because the variables nAlice and nBeatriz already contain memory addresses. See function statement:

void recebeNumCartas(int *nAlice, int *nBeatriz)

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

recebeNumCartas(&nAlice, &nBeatriz);

Thus the scanf is getting exactly what he expects.

  • In which line does this occur? I am half lost

  • I am still editing the question, I will explain everything that is occurring

  • you understand what’s happening now?

  • Got it, I’ll pay more attention to these details, thank you!

Browser other questions tagged

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