#include <stdio.h>
int main()
{
int num1;
int *p;
p=&num1;
printf("Give a value\n");
scanf("%d", &num1);
printf("\n%d", num1);
f2(&num1);
printf("%d", *p);
return 0;
}
void f2(int *p)
{
*p *= *p;
}
A call by reference program just to return the square of a value
Well, the problem is that if I do not use printf the expected output is correct (e.g. 2*2=4)
However, if I include:
printf("\n%d", num1);
and run the programm I will take a non expected value (e.g. 2*2=24)
These two calls of printf result of outputting two values in the same line without a space.
printf("\n%d", num1);
f2(&num1);
printf("%d", *p);
If you want to make the output less confusing then for example write
printf("\n%d", num1);
f2(&num1);
printf("\n%d\n", *p);
There are two problems in your code.
You need to declare void f2(int* p) before using it. Depending on your platform you might get away with it. But a sane compiler should give you at least a warning (which should be considered as an error).
Sloppy format strings in your printfs make the output look wrong.
Try this:
#include <stdio.h>
void f2(int* p); // you need to declare this, otherwise you'll get a
// warning you should always conside as an error
int main()
{
int num1;
int* p;
p = &num1;
printf("Give a value\n");
scanf("%d", &num1);
printf("\nnum1 = %d\n", num1); // format string more explicit
f2(&num1); // warnig here if f2 is not declared as above
printf("*p = %d\n", *p); // format string more explicit
return 0;
}
void f2(int* p)
{
*p *= *p;
}
There are several problems with this code.
You need to either:
a. declare a prototype for f2. You can do this by putting the following code before your main
void f2(int *p);
b. put the entire f2 function before main (and this is the route that I'd probably choose - but questions of style are the cause of countless pointless wars.
The output is unclear. By not putting \n in your printf statement you're running the output of the two print statements together. Use this instead:
printf("\n%d\n", num1);
Pretty printing greatly improves readability. And don't be afraid of giving functions meaningful names.
On balance, I think I'd write your code like so:
#include <stdio.h>
void square(int *p) {
*p *= *p;
}
int main(int argc, char *argv[]) {
int num1;
int *p;
p = &num1;
printf("Give a value: ");
scanf("%d", &num1);
printf("\n%d squared is equal to: ", num1);
square(&num1);
printf("%d\n", *p);
return 0;
}
#include <stdio.h>
#include <math.h>
void f2 (int *p)
{
*p = pow(*p, 2); // equal with *p *= *p;
}
int main ()
{
int num1;
int *p; // p is pointer variable that points to num1
// type of num1 and p must be the same (int).
p = &num1; // p is address of num1
printf ("Give a value: ");
scanf ("%d", p); // p is address of num1
printf ("\nnum1 before: %d", *p); // *p is num1 (content of p)
f2 (p);
printf ("\nnum1 after: %d", *p); // missing \n in here
return 0;
}
Related
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.
I am working on a project that requires me to read user inputs as pairs of integers and then store them in an array. So, I have created a function that does this. However, I for some reason get a segmentation fault everytime the last input is entered. Here is my code:
int userInput(int *arrayPtr){
int numberPairs, i, numberElements;
printf("%d", sizeof(int));
printf("How many pairs of integers? ");
scanf("%d", &numberPairs);
numberElements = numberPairs*2;
arrayPtr = malloc((numberElements*sizeof(int)) + 64);
for(i = 0; i < numberElements; i+=2){
int first,second;
printf("\nEnter pair: ");
printf("Before scanf");
scanf("%d %d", &first, &second);
printf("%d", first);
arrayPtr[i] = first;
arrayPtr[i+1] = second;
}
printf("%d", numberPairs);
return numberPairs;
}
Here is how I call the function:
int main(){
int *arrayPtr, numberPairs;
numberPairs = userInput(arrayPtr);
multiplyPairs(arrayPtr, numberPairs);
free(arrayPtr);
}
At the moment, I am mainly trying to make the for loop execute in its entirety, but for some reason it always seg faults on the last iteration. For example, if my input for the pairs was 1 2, 3 4, 5 6, my ouput would be 1 3 and then a seg fault (this output is referring to the print statement in the for loop). I have spent a few hours trying to debug this code as well as having other students look at it, and I can not figure out what is wrong. If you could point me in the right direction I would greatly appreciate it. Thanks.
UPDATE: I copied and pasted the code into a new file and it works as intended. Thank you to everyone who told me about other elements of my code that were wrong.
You need this:
int userInput(int **arrayPtr){
int numberPairs, i, numberElements;
printf("%d", sizeof(int));
printf("How many pairs of integers? ");
scanf("%d", &numberPairs);
numberElements = numberPairs*2;
*arrayPtr = malloc((numberElements*sizeof(int)) + 64);
for(i = 0; i < numberElements; i+=2){
int first,second;
printf("\nEnter pair: ");
printf("Before scanf");
scanf("%d %d", &first, &second);
printf("%d", first);
(*arrayPtr)[i] = first;
(*arrayPtr)[i+1] = second;
}
printf("%d", numberPairs);
return numberPairs;
}
int main(){
int *arrayPtr, numberPairs;
numberPairs = userInput(&arrayPtr);
multiplyPairs(arrayPtr, numberPairs);
free(arrayPtr);
}
Explanation using a very simple example
You want to write a function that mutiplies the first with it's second argument and stores the value in the third agrument.
So you try this:
void Multiply(int a, int b, int r)
{
r = a * b;
}
int main(){
int result = 0;
Multiply(3, 4, result);
printf ("result = %d\n", result);
return 0;
}
And you expect the output is result = 12. But you get result = 0. The reason is that when a function parameter is modified, the function argument of the caller won't be modified because the parameters are passed by value (it's like that in C and in most other programming languages). BTW what should happen if you dont pass a variable as 3rd argument but a constant: for example Multiply(3, 4, 5); ?
If you want your function to modify an argument, you have to pass a pointer to the argument to the fonction and modify the pointed value in the function:
Following example shows what to do:
void Multiply(int a, int b, int *r)
{
// r points to the variable passed as third argument
*r = a * b;
}
int main(){
int result = 0;
// here we pass the pointer to result
Multiply(3, 4, &result);
printf ("result = %d\n", result);
return 0;
}
The code need to send to the function an int must to send just int and show the changes after the function. so I tried this:
int main(void)
{
int number = 0;
printf("Please enter some number: \n");
scanf("%d", &number);
printf("the number that you entered: %d\n", number);
inc(number);
printf("After the 'inc' function, your number is: %d\n", number);
system("PAUSE");
return 0;
}
/*
*/
void inc(int x)
{
int* px = &x;
*px= *px+1;
}
it's prints just the same number and doesn't change at all. help?
you must pass the parameter as a pointer
void inc(int *px)
{
*px= *px+1;
}
in your code you are just modifying the functions local copy of x
A hacktacularly terrible hackaround:
inc((int)&number);
// ...
void inc(int n)
{
++*(int*)n;
}
Don't do this. It won't work on all but certain archaic architectures.
I am trying to make a program that scans 3 ints and then passes them through a function that sort them by this way- the biggest number will be at 'num3', the second will be at 'num2' and the lowest one will be at 'num1' but for some reason the program crashes when it gets to the sort function.
#include <stdio.h>
#include <stdlib.h>
void swap(int* a, int* b);
void changer(int* num1, int* num2, int* num3);
int main()
{
int num1 = 0;
int num2 = 0;
int num3 = 0;
printf("Please enter your value for 'num1': ");
scanf("%d", &num1);
getchar();
printf("Please enter your value for 'num2': ");
scanf("%d", &num2);
getchar();
printf("Please enter your value for 'num3': ");
scanf("%d", &num3);
printf("\nYour nums before- \n");
printf("num1 == %d\n", num1);
printf("num2 == %d\n", num2);
printf("num3 == %d\n", num3);
changer(&num1, &num2, &num3);
printf("\nYour nums after- \n");
printf("num1 == %d\n", num1);
printf("num2 == %d\n", num2);
printf("num3 == %d\n", num3);
system("PAUSE");
return 0;
}
void changer(int* num1, int* num2, int* num3)
{
if (*num1 > *num3)
{
swap(*num3, *num1);
}
else if (*num1 > *num2)
{
swap(*num1, *num2);
}
if (*num2 > *num3)
{
swap(*num3, *num2);
}
}
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
You should not dereference the pointers when you pass them to swap() since it takes int * and you would be passing int thus causing undefined behavior and in your case a crash. The compiler should warn about incompatible parameters.
Change every occurrence of
swap(*num1, *num2);
/* ^ ^ remove these */
with
swap(num1, num2);
swap(int*, int*) expects the integer pointer to be passed in, assume the value of num1 = 0 and num2 = 2 and when you pass these values to swap(), by dereferencing you are invoking like this swap(0, 2) or on 32 bit system
swap(0x00000000, 0x00000002)
Inside swap(int* a, int* b) you dereference the memory location 0x00000000 (not the memory pointed to by a) at the line,
int temp = *a;
and then you dereference 0x00000002 b at this line and trying to assign it to 0x00000000 (by dereferencing *a)
*a = *b;
You are generating
Memory access violation condition.
which is causing the crash. Summarizing, please do not ignore compiler warnings. Compiler raises warning on the line where you are making swap() calls.
'int *' differs in levels of indirection from 'int'
Both functions take integer pointers (i.e., memory addresses of integers) as arguments. So, the values of the arguments a, b, num1, num2, and num3 must ALWAYS be memory addresses of integers. In the function changer, values of the variables num1, num2, and num3 are ALREADY memory addresses. When you write *num1, value of *num1 is integer but not the memory address of an integer. So, you need to call the function swap as follows:
swap(num3, num1);
swap(num1, num2);
swap(num3, num2);
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);
}