user5450944
user5450944

Reputation:

This thing is giving me error. C Language

How can I fix this? I want to scanf() a value for d, how can I do it? I need some help please. Appreciate that.

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

void LerDeputados(int d) {
    printf("Indique o número de deputados a repartir: ");
    scanf("%d",&d);
}
int main(void) {
    int d;
    LerDeputados(d);
    printf("%d",d);

    return 0;
}

Upvotes: 0

Views: 72

Answers (3)

LBes
LBes

Reputation: 3456

There are some errors in your code. First of all you need to return the value that you get from scan in the LerDeputados(int d) function. Also you need to assign this value to the d you create in your main() Change your code to:

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

int LerDeputados() {
    int d ;
    printf("Indique o número de deputados a repartir: ");
    scanf("%d",&d);
    return d ;
}
int main(void) {
    int d;
    d = LerDeputados();
    printf("%d",d);

    return 0;
}

Or you can use pointers (needs a more advanced level though)

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

void LerDeputados(int* pd) {
    printf("Indique o número de deputados a repartir: ");
    scanf("%d",pd);
}
int main(void) {
    int d;
    LerDeputados(&d);
    printf("%d",d);

    return 0;
}

My piece of advice would be to read some good C book before going further into the world of programming.

Hope it helps ;)

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409166

The problem here is that when you pass the variable d to your LerDeputados function, it's passed by value, which means that it is copied. The value is properly changed inside the function, but it's only changing the copy, and changing a copy will of course not change the original.

What you need to do here is to pass the variable by reference. Unfortunately C doesn't have that, but it can be emulated by using pointer. In other words, you need to pass a pointer to the variable d to your LerDeputados function.

Like

void LerDeputados(int *d) { ... }

Then call it with the address-of operator:

LerDeputados(&d);

Upvotes: 4

Haris
Haris

Reputation: 12270

You need to read the basics of C..

Change the scanf() to

scanf("%d",&d);

A little explanantion

scanf() needs the address of the variable in which it will store the read value. An to get the address of an int variable, you the & operator before it.

That was to solve the error


Now, in your code, variable d in void LerDeputados(int d) is a local variable, which is completely different from the d in main(). This is happening because you are passing the vallue of d to void LerDeputados(int d). You have to pass the address to void LerDeputados().

Chnage your code to

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

void LerDeputados(int* d) {
    printf("Indique o número de deputados a repartir: ");
    scanf("%d",d);
}
int main(void) {
    int d;
    LerDeputados(&d);
    printf("%d",d);

    return 0;
}

Upvotes: 1

Related Questions