Error in code, C

Asked

Viewed 5,957 times

2

I created an extremely simple code just to test the Code::Blocks, but no matter what I do, always returns the following error:

collect2.exe: error: ld returned 1 exit status

I still don’t understand what I’m missing. the code goes here:

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

int main(){
   int A;
   printf("Digite um valor: ");
   scanf("%d", &A);
   printf("O valor digitado foi: ", &A);
   return 0;
}
  • This message has nothing to do with the code, it is perfectly compilable (although it does not do what you want, as seen in the dvm response). There is some problem with your compiler. You are sure that this is the only message shown? Most likely you have some before her explaining what happened.

4 answers

3

The program error is in the following line:

   printf("O valor digitado foi: ", &A);

Correct:

   printf("O valor digitado foi: %d", A);

Note that to reference a variable and display it on the screen, it is necessary to use the '%d' inside the sentence and, after the comma, it is NOT necessary to use the '&' character (this is only required for referencing in the 'scanf'').

1

Things to consider:

  1. No input check: Nothing guarantees that an "int" will be typed in stdin
  2. No scanf check: Nothing guarantees that the whole received will be "sufficient" to house the same on a die of the type "int"
  3. Lack of spacing: It is interesting that all messages on console has at least one line break ( n)
  4. No formatting: Every parameter passed to printf needs to have a specifier according to the type of the variable (%d, %p , %i ....)
  5. Incorrect representation of the value stored by A: Use &A on printf will pass the "memory address" that the value of A resides:

(Address) printf("Valor: %p\n",&A)

(Valor) printf("Valor: %d\n",A)

If it is a specific problem in the build process, you can pass a "-v" to deduce whatever it is.

1

You have an error related to printf line, it should be written as follows:

printf("O valor digitado foi: %d\n", A);

Variable A in the case of scanf is passed as a reference so that it can change it, already in the printf is only informed so that it can display the contents of this.

1

collect2.exe: error: ld returned 1 exit status
                     ^^

ld is the "Linker": the part of the compiler that 'mixes' your code with the existing code (the scanf(), for example).

Apart from the &A used in the printf(), that should just be a, your program has no error. This error does not prevent the compilation, but the results will be strange.

Check your compiler configuration, especially the Linker part, the library paths, etc.

Browser other questions tagged

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