LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Problem with a verx simple c program. (https://www.linuxquestions.org/questions/programming-9/problem-with-a-verx-simple-c-program-542395/)

Kanesoban 04-01-2007 11:45 AM

Problem with a verx simple c program.
 
Helo.

I wrote a very simple program in Kate:

#include <stdio.h>
main ()
{
int number;
printf("A number please.\n");
scanf("%d",number);
printf("%d\n",number);
return 0;
}

I compiled it with gcc, and then i cant execute it. It says "Segmentation fault"

rednuht 04-01-2007 11:53 AM

not sure you can return an integer with out specifying main returns it first
Code:

int main() {

ntubski 04-01-2007 11:56 AM

you should do
Code:

scanf("%d",&number);
scanf needs the address of an int so it can change the value of the variable.

Kanesoban 04-01-2007 04:45 PM

Quote:

you should do
Code:

scanf("%d",&number);
That was the problem. Interestingly, i don't remember reading in any tutorial, that "&" is needed when using scanf. Anyways, thank you.

ntubski 04-02-2007 09:14 AM

I hope you didn't get the impression that & is a "magic" operator to use with scanf. If you have gotten to the end of any C tutorial without learning about pointers please find a better a tutorial.

rufius 04-02-2007 09:18 AM

Quote:

Originally Posted by Kanesoban
That was the problem. Interestingly, i don't remember reading in any tutorial, that "&" is needed when using scanf. Anyways, thank you.

The ampersand (&) tells the program to refer to the memory address of the variable, rather than the variable name itself. Basically it tells scanf to put the data in &number's memory place.


All times are GMT -5. The time now is 04:46 AM.