I am getting my head wrapped around pointers, and I get a segmentation fault on this code, for no apparent reason.
Basically this works:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *a;
printf("Please enter a number: ");
scanf("%i", *(&a));
printf("1st number is: %i\n", *a);
}
And this doesn't:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *a, *b;
printf("Please enter a number: ");
scanf("%i", *(&a));
printf("Please enter the second number: ");
scanf("%i", *(&b));
printf("1st number is: %i\n", *a);
printf("2nd number is: %i\n", *b);
}
Just why?
You have declared two pointers to integers, without ever declaring or allocating any memory that those pointers could point to. Rather, declare two integers on the stack, and pass pointers to them:
int a, b;
scanf("%i", &a);
scanf("%i", &b);
printf("Numbers: %i %i\n", a, b);
The fact that your first example works is out of pure luck--it's very likely that a seemingly-valid pointer was left on the stack at just the right location for the example to barely work.
Neither of them should work. If they work it's because undefined behavior includes the behavior of working properly.
Your main problem is that you are writing to an uninitialized pointer. I don't see why you want to use pointers here. If you want to, you have to make them point to something. This is one way:
int x;
int *a = &x; // Pointer that points to x
Or you could just remove the pointers completely:
int a;
printf("Please enter a number: ");
scanf("%i", &a);
printf("1st number is: %i\n", a);
And doing *(&a) is just unnecessary. It means exactly the same as a.
Related
#include <stdio.h>
#include <math.h>
int main()
{
int numbers[5];
printf("Enter your first number:%d");
scanf("%d", numbers[0]);
printf("Enter your second number:%d");
scanf("%d", numbers[1]);
numbers[3]=numbers[0]+numbers[1];
printf("Your desired result is:%d",numbers[3]);
return 0;
}
I seem to find no problem in the code but it won't even let me input numbers in the array I declared
The issue is in the second argument of scanf.
scanf("%d", numbers[0]);
it expects an address of where to write your input to but you are passing the value of numbers[0]. So scanf will write to whatever is in numbers[0] which is an int, not a pointer.
Take the address of numbers[0] by changing it to:
scanf("%d", &numbers[0]);
Im trying to understand pointers as function parameters, and in one of the programs there is a segmentation error I can't fix. Firstly, why to use pointers in function arguments? and Why is this error showing?
#include <stdio.h>
void square_it(int* a)
{
printf("The final value is: %d\n", *a * *a);
}
int main()
{
int* input;
puts("This program squares the input integer number");
puts("Please put the number:");
scanf("%d", &input);
square_it(input);
return 0;
}
int* input; does not allocate memory for an int. It mearly makes it possible to make input point at an int (allocated elsewhere). Currently, by dereferencing it (like you do with *a), you make your program have undefined behavior. If you really want an intermediate pointer variable for this, this example shows how it could be done:
#include <stdio.h>
void square_it(int *a) {
*a *= *a; // same as *a = *a * *a;
}
int main() {
int data;
int* input = &data; // now `input` points at an `int`
puts("This program squares the input integer number");
puts("Please put the number:");
// check that `scanf` succeeds:
if(scanf("%d", input) == 1) { // don't take its address, it's a pointer already
square_it(input);
// since `input` is pointing at `data`, it's actually the value of `data`
// that is affected by `scanf` and `square_it`, which makes the below work:
printf("The final value is: %d\n", data);
}
}
Without an intermediate pointer variable:
#include <stdio.h>
void square_it(int *a) {
*a *= *a;
}
int main() {
int input; // note that it's not a pointer here
puts("This program squares the input integer number");
puts("Please put the number:");
if(scanf("%d", &input) == 1) { // here, taking the address of `input` makes sense
square_it(&input); // and here too
printf("The final value is: %d\n", input);
}
}
Without any pointers at all, it could look like this:
#include <stdio.h>
int square_it(int a) {
return a * a;
}
int main() {
int input;
puts("This program squares the input integer number");
puts("Please put the number:");
if(scanf("%d", &input) == 1) { // here, taking the address of `input` makes sense
int result = square_it(input);
printf("The final value is: %d\n", result);
}
}
This is the working code:
#include <stdio.h>
void square_it(int* a)
{
printf("The final value is: %d\n", *a * *a);
}
int main()
{
int i = 0;
int* input = &i;
puts("This program squares the input integer number");
puts("Please put the number:");
scanf("%d", input);
square_it(input);
return 0;
}
There are some errors in the original code:
According to the man-pages to scanf, it takes a format string and then the address of where to store the input.
You gave it the address of a pointer (eg. an int**), which is not what scanf expects.
Also you need to provide memory to store the input in. The scanf string tells that you want an integer as input. In the above code snippet that is i.
input points to i, so i can give the int*, that is input to scanf. scanf will then write into i. We can then go ahead and put the address of i into the sqare_it function.
Since we did not use the heap, we don't need to worry about memory management.
This question already has answers here:
Scanning with %c or %s
(2 answers)
Why does C's printf format string have both %c and %s?
(11 answers)
Closed 4 years ago.
Writing a simple code that's suppose to scan an integer and a character and then write them out.
my input is 1a and the output should be 1a but i'm getting 0 on the integer spot. have a pretty basic understanding of c so may have missed something that's pretty obvious thanks in advance.
#include <stdio.h>
int main()
{
int a;
char b;
scanf("%d", &a);
scanf(" %s", &b);
printf("%d", a);
printf("%s", &b);
}
b is a character so replace %s with %c, moreover
scanf() takes & before the variable as it want to store the variable refering to that address.
2.printf() Just outputs the value to the console present in that varaible.
Thereby no need to use & inside it
CORRECTED CODE:
#include <stdio.h>
int main()
{
int a;
char b;
scanf("%d", &a);
scanf(" %c", &b);
printf("%d", a);
printf("%c", b);
}
b is a char, %s is for string input so adds trailing 0 after b and you can get a crash. Use %c to input char.
You basically want this:
#include <stdio.h>
int main()
{
int a;
char b[100]; // array of 100 chars
scanf("%d", &a);
scanf("%s", b);
printf("%d", a);
printf("%s", b);
}
To fully understand this, you need to read the chapters dealing with scanf and the one dealing with strings in your C text book.
you can try it:
#include <stdio.h>
int main()
{
int a;
char b;
scanf("%d", &a);
scanf(" %c", &b);
printf("%d", a);
printf("%c", b);
}
I have an error code I do not understand:
format %d expects type int, but argument 2 has type int *
I do not know the difference between int and int *. I did not know there were different types of int, and cannot find any note of it on webpages about printf and scanf key letters.
The code is as follows:
#include <stdio.h>
#include <math.h>
int main(void)
{
int X = 0, Y = 0, A = 0, D = 0;
printf("This program computes the area of a rectangle ");
printf("and its diagonal length.");
printf("Enter Side 1 dimentions: ");
scanf("%d", &X);
printf("Enter Side 2 dimentions: ");
scanf("%d", &Y);
/* Calc */
A = X * Y;
D = pow(X,2) + pow(Y,2);
D = pow(D, 1 / 2);
/* Output */
printf("Rectangle Area is %d sq. units.", &A);
printf(" Diagonal length is %d.", &D);
return 0;
}
The error references the last two printf's:
printf("Rectangle Area is %d sq. units.", &A);
printf(" Diagonal length is %d.", &D);
Additionally, this program was originally written using floats (declaring X,Y,A, and D as float and using %f). But that gave an even stranger error code:
format %f expects type double, but argument 2 has type float *
I knew that %f is used for doubles and floats, so I could not understand why I had this error. After I got the error code about floats/doubles I tried changing everything to int (as shown in the above code), just to check. But that delivered the error code at the top of this post, which I do not understand either.
I've been using the gcc compiler.
Would someone explain what's being done wrong?
The problem is that you're trying to pass pointers to the printf function. Here's what your code looks like:
printf("Rectangle Area is %d sq. units.", &A);
printf(" Diagonal length is %d.", &D);
A is the int variable, but &A is a pointer to the int variable. What you want is this:
printf("Rectangle Area is %d sq. units.", A);
printf(" Diagonal length is %d.", D);
int* means a pointer to an int object. this is what you get because you use & before the variable name (i.e &A in your code)
You can read this to understand more about pointers and references, but basically if you omit the & before the variable names, it will work fine.
Why passing pointers to printf("...%d...", &D)?
Take a look to pointers explanation:
http://www.codeproject.com/Articles/627/A-Beginner-s-Guide-to-Pointers
And to simplified printf() manual:
http://www.cplusplus.com/reference/cstdio/printf/
int d = 1;
printf("I'm an integer: %d", 42); // OK, prints "...42"
printf("I'm an integer too: %d", d); // OK, prints "...1"
printf("I'm a pointer, I have no idea why you printing me: %p", (void*)&d); // OK, prints "...<address of d>", probably not what you want
printf("I'm compile-time error: %d", &d); // Fail, prints comiper error: 'int' reqired, but &d is 'int*'
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Hi I have written a c program that reads in 2 values then swaps them and prints the new values except the second value keeps showing 0. For example it you enter 10 for 'a' and 8 tor 'b', then a will be 8 but b will be 0. Does anyone know the solution to fix this? Here is the code:
#include <stdio.h>
int getData()
{
int a, b;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
return(a, b);
}
void swapValues(int a, int b)
{
printf("The value of a is: %d", b);
printf("\nThe value of b is: %d", a);
return;
}
int main()
{
int a, b = getData();
swapValues(a, b);
return(0);
}
return (a, b);
doesn't do what you think it does, it's a misapplication of the comma operator.
The expression op1, op2 evaluates both op1 and op2 but gives you the value of op2. So it's not passing back a couple of values (although some languages like Python can do this sort of thing).
Similarly,
int a, b = getData();
won't grab the mythical two values returned from getData(). Rather it will set a to an indeterminate value and set b based on the single value returned from the function.
I would be looking at something like this:
#include <stdio.h>
int getData (char *which) {
int val;
printf ("Enter value for %s: ", which);
scanf("%d", &val);
return val;
}
void swapValues (int a, int b) {
printf("The swapped value of a is: %d\n", b);
printf("The swapped value of b is: %d\n", a);
}
int main (void) {
int a = getData ("a");
int b = getData ("b");
swapValues(a, b);
return 0;
}
You should also keep in mind that, if you actually want to swap the variables a and b and have that reflected back to main(rather than just print them as if they've been swapped), you'll need to pass pointers to them and manipulate them via the pointers.
C is a pass-by-value language meaning that changes to function parameters aren't normally reflected back to the caller. That would go something like this:
void swapValues (int *pa, int *pb) {
int tmp = *pa;
*pa = *pb;
*pb = tmp;
}
:
swapValues (&a, &b);
// a and b are now swapped.
You have unnecessarily complicated the whole thing.For one, something like return(a,b) is absurd in C.Further, if you intend to swap, why are you passing b as argument for the printf() meant to print 'a' and passing a to the printf() of 'b'?Anyways,here's a modified code that keeps it simple and gets the job done.
#include <stdio.h>
void swapValues()
{
int a, b,tem;
printf("Enter first number: ");
scanf("%d", &a);
printf("\nEnter second number: ");
scanf("%d", &b);
tem=a;
a=b;
b=tem;
printf("\nThe value of a is: %d", a);
printf("\nThe value of b is: %d", b);
}
int main()
{
swapValues();
return(0);
}
First of all you can't return more than one value in C. The way around that is to return a struct or pass the values address.
void getData(int *a,int* b)
{
//int a, b;
printf("Enter first number: ");
scanf("%d", a); // look here you passed the address of a to scanf
// by doing that scanf can write to a
printf("Enter second number: ");
scanf("%d", b);
//return(a, b);
}
The old main:
int main()
{
int a, b = getData(); // b gets the return value from getData()
// but a is still uninitialized
//to call the new function you have to do the following
int a,b;
getData(&a,&b);
swapValues(a, b);
return(0);
}
You cannot return multiple values from a C function. I'm not even sure why the statement return(a, b) compiles.
If you want to return more than value from a function you should either put them into an array or a structure. I'm going to use a structure to demonstrate one way to do this correctly. There are many ways to do this, but this one modifies you code the least.
struct TwoNums{
int a;
int b;
};
TwoNums getData()
{
/* This creates a new struct of type struct TwoNums */
struct TwoNums nums;
printf("Enter first number: ");
scanf("%d", &(nums.a));
printf("Enter second number: ");
scanf("%d", &(nums.b));
return(a, b);
}
void swapValues(int a, int b)
{
printf("The value of a is: %d", b);
printf("\nThe value of b is: %d", a);
return;
}
int main()
{
/* Get the whole structure in one call */
struct TwoNums nums = getData();
/* Call the swap function using fields of the structure */
swapValues(nums.a, nums.b);
return 0;
}
The first:
getData() function is written incorrectly.
You can not return more than one parameter from the function in C. So you can to separate data reading, or use pointers as below:
void getData(int* a, int* b) {
printf("Enter first number: ");
scanf("%d", a);
printf("Enter second number: ");
scanf("%d", b);
}
In main()
int a, b;
getData(&a, &b);
The second:
swapValues(int a, int b) does not swap the data.
More correct:
void swapValues(int* a, int* b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
without using temporary variable.
So try this code
#include <stdio.h>
int swape()
{
int a,b;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
a=a+b;
b=a-b;
a=a-b;
printf("The value of a is: %d", a);
printf("\nThe value of b is: %d", b);
}
int main()
{
swape();
return(0);
}