This is a test case for something larger, which is why it is written the way is. How could I make this bit of code so that a's value would keep incrementing? In my project I call a function that parses a line from a file. I need to set values of a struct to certain values that were set in the function call (the parameters of the function were initialized in the main function, like the code below).
int increment(int a)
{
a++;
return 0;
}
int main()
{
int a =0;
int b =0;
while( b<5){
increment(a);
b++;
cout << "a is: " << a << ". And b is: " << b << "\n";
}
system("PAUSE");
}
Thanks.
Pass its address to increment
void increment(int *a){
(*a)++;
}
increment(&a);
//Using the address of operator pass in the address of a as argument
You could use a pointer: See Passing by reference in C for a similar question.
Also, you could just modify your increment function to return the incremented value of a, and call it in main like the following:
a = increment(a);
You could:
Declare static int a = 0; return a++;
Change the signature to int increment( int* a ) and return *a++;
Declare a in file scope of the same source file as increment()
Make a global
Do this in C++ and pass a by reference
You are passing a by value, so the value of a can never be changed.
One solution is:
int increment (int a) { return a + 1; }
Then in your loop:
a = increment(a);
Another solution is to pass a by reference (a pointer)
void increment (int *a) { *a = *a + 1; }
and in the loop
increment(&a);
Related
i have a simple program like this :
#include<stdio.h>
void add(int *nb)
{
*nb += 1;
}
int f(int nb, void (*add)(int *))
{
if (nb < 5)
f(nb, add(&nb));
return (nb);
}
int main() {
int b = 5;
int a = f(b, add);
printf("%d\n", a);
}
i want to call f recursively until nb become greater or equal to 5, but when i compile the program , the gcc compiler show something like this :
error: passing 'void' to parameter of incompatible type 'void (*)(int *)'
can anyone help me please?
I'm not completely certain as to what you are trying to do with your function, but I took a stab at what I think you might be attempting to do:
#include<stdio.h>
void add(int *nb)
{
*nb += 1;
}
int f(int nb, void (*function)(int *))
{
function(&nb);
if (nb < 5)
f(nb, function);
return (nb);
}
int main() {
int b = 5;
int a = f(b, add);
printf("%d\n", a);
}
Now your function f accepts a function-pointer to a void function that takes an int * as an argument (I renamed this argument to function so it doesn't conflict with your existing function add). It proceeds to call said function and pass in a pointer to nb to function.
What you were doing was passing in the result of add(&nb) into the function f as an argument (which said function is a void so it does not return anything) instead of passing in a pointer to the function.
The line f(nb, add(&nb)); doesn't make sense. You need to call the function somewhere, but not on the same line as where you pass the function pointer on, recursively.
Overall the program doesn't make much sense. I have no idea what you are trying to do, perhaps something similar to this?
#include<stdio.h>
void add(int *nb)
{
*nb += 1;
}
void f(int* nb, void (*add)(int *))
{
add(nb);
if (*nb < 5)
{
f(nb, add);
}
}
int main() {
int a = 5;
f(&a, add);
printf("%d\n", a);
}
Will print 6 since the add is called once. The name add as function parameter to f is also mighty confusing, so better come up with another name for it.
Passing add(&nb) as an argument passes the returned value of add with the argument &nb. The function signature for f requires a function pointer, which can be passed as:
f(nb, add)
Also, even if you were actually trying to pass the returned value of add, that would be undefined behavior since it is of type void.
As Christian pointed out in the comments, the problem is on the recursive call line:
f(nb, add(&nb));
If I understand correctly you are trying to increase nb using the function you receive as a pointer; here however you first pass nb unchanged (and as a value, not by reference), and then call the add function.
In the second argument the compiler is expecting a function pointer, but instead it receives the return value of the add(&nb) function call, which is void.
Also, in case nb is < 5 you need to return the recursive call.
The correct procedure would be:
#include<stdio.h>
void add(int *nb)
{
*nb += 1;
}
int f(int nb, void (*add)(int *))
{
if (nb < 5) {
add(&nb);
return f(nb, add);
}
return (nb);
}
int main() {
int b = 1;
int a = f(b, add);
printf("%d\n", a);
}
It almost seems like you're trying to use lazy evaluation, but C doesn't have that!
int main ()
{
int a, b;
call(&b);
printf("%d, %d",a , b);
}
void call(int *ptr)
{
}
Desired output:
50, 100
How to write the call function so as to modify both the variables to get the desired output??
Not sure where the values 50 and 100 are coming from or exactly what you are asking but maybe this will help with your question.
Since C is pass by value you need to send pointers to actually change the value inside another function.
Since the call function will have pointer values you need to dereference the pointers before changing the value.
Here is an example:
void call(int *a, int *b)
{
*a = 50;
*b = 100;
}
int main()
{
int a, b;
call(&a, &b);
printf("%d, %d\n", a, b);
}
While we are exploring the many ways this output could be achieved, consider that the function could store state in a static variable:
#include <stdio.h>
void call(int *ptr);
int main(void)
{
int a, b;
call(&a);
call(&b);
printf("%d, %d\n",a , b);
}
void call(int *ptr)
{
static int store = 0;
store += 50;
*ptr = store;
}
Program output:
50, 100
Note that you may also be able to do this as follows, without any modifications to main(). But be warned that this method invokes undefined behavior! It is undefined behavior to write to a location past the end of an array object, and in the case of a and b, these are considered to be array objects of size 1. Here we are assuming that this write will work, and that a and b are stored next to each other in memory. We further assume that a has the higher address in memory.
I would say that you should never do this, but I can see no other way to modify a from the function call() without knowing the address of a. You have been warned.
void call(int *ptr)
{
*ptr = 100;
*(ptr + 1) = 50;
}
Try something like this:
void call(int *ptr)
{
*ptr = 100;
}
int main ()
{
int a, b;
a = 50;
call(&b);
printf("%d, %d",a , b);
}
See demo
Maybe you want this:
int main ()
{
int a, b;
call(&a, &b);
printf("%d, %d",a , b);
}
void call(int *ptr1, int *ptr2)
{
*a = 50;
*b = 100;
}
To change a local variable in function a by calling function b you have two options.
1) Let function b return a value that you assign to the variable in function a. Like:
int b() {return 42;}
void a()
{
int x = b();
printf("%d\n", x);
}
This does, however, not seem to be what you are looking for.
2) Pass a pointer to the variable to function b and change the variable through that pointer
void b(int* p) // Notice the * which means the function takes a pointer
// to integer as argument
{
*p = 42; // Notice the * which means that 42 is assigned to the variable
// that p points to
}
void a()
{
int x;
b(&x); // Notice the & which means "address of x" and thereby
// becomes a pointer to the integer x
printf("%d\n", x);
}
int main()
{
int a,b;
call(&b);
printf("%d, %d\n", a,b);
}
int call(int *ptr)
{
int *m;
m = ptr++;
*ptr = 50;
*m = 100;
}
Let's say a have a pointer as a parameter, why doesn't it's value remain modified after the and of a function, and i have to use this syntax :
void function_name (int **p)
{
// code
}
and in main() :
int *v;
function name (&v);
I want to specify that i use a pointer to a struct type as a parameter.
C passes arguments by value. If you want to modify something in a function and make the modification take effect in the calling function, a pointer to the variable in the calling function has to be passed. Otherwise, any changes made to the variable in a function are only local changes and does not affect the value of the variable in the calling function.
Let's start with an int type variable.
void foo(int x)
{
x = 10;
}
int main()
{
int a = 100;
foo(a); // Value of a does not change in this function
}
In the above program, the value of a remains 100 in main. The line
x = 10;
in foo only affects the value of the variable in foo. To make the change in foo affect the value in main, you'll need to pass a pointer to a.
void foo(int* x)
{
*x = 10;
}
int main()
{
int a = 100;
foo(&a); // Value of a changes in this function
}
Take that analogy to a pointer.
void bar(int* x)
{
x = malloc(10*sizeof(int));
}
int main()
{
int* ptr = NULL;
bar(ptr); // Value of ptr does not change in this function
}
bar allocates memory for an array of 10 ints and assigns the memory to x but that change is local. main does not see it. In main, ptr is still NULL. To make the change in bar affect ptr, a pointer to ptr has to be passed to bar.
void bar(int** x)
{
*x = malloc(10*sizeof(int));
}
int main()
{
int* ptr = NULL;
bar(&ptr); // Value of ptr changes in this function
}
In C, arguments are passed by value. This means that when you pass an argument to a function, a copy of that variable is made. For example
int main()
{
int x = 6;
repchar(x, 'r');
printf("%d\n", x);
return 0;
}
void repchar(int n, char c)
{
while (--n >= 0)
putchar(c);
}
This program prints the letter r six times, and then at the last printf, prints out 6, not -1. The reason is that when repchar was called, x was copied. That way, when repchar decrements n, the caller's copy is not changed.
If we passed a pointer, however, n would be modified.
int main()
{
int x = 6;
repchar(&x, 'r');
printf("%d\n", x);
return 0;
}
void repchar(int *n, char c)
{
while (--(*n) >= 0)
putchar(c);
}
Instead of the variable being copied, now the address of the variable is being copied. Inside of repchar, *n is being counted down. This accesses the value that is being referenced by n, which is the same address as x and decrements it. As a result, the last printf will give -1.
Here is my code that works. The function initializes the array, a, to values 0 - 3
int main(void)
{
int a[4];
pointer(a);
return 0;
}
void pointer(int* a)
{
int *p, i;
p = a;
for(i = 0; i < 4; i++)
{
*a++ = i;
printf(" %d", p[i]);
}
}
But when I combine it all into main(), it no longer works.
int main(void)
{
int a[4], *p, i;
p = a;
for(i = 0; i < 4; i++)
{
*a++ = i;
printf("%d", p[i]);
}
return 0;
}
Instead, it prints out memory addresses or something. It works when I dynamically allocate a[], so I'm guessing it has something to do with the way a[] is managed in memory. Can someone tell me why the second main() doesn't work?
In the function pointer, the argument a is a pointer. But in main, a is an array, you can't modify an array name, so *a++ = i is invalid.
I can't even compile your code, and the error illustrates why:
$ gcc -o foo foo.c
./foo.c:9:11: error: cannot increment value of type 'int [4]'
*a++ = i;
~^
1 error generated.
You aren't actually using a pointer in your code at all. If you change it as follows, it works as you expect:
#include <stdio.h>
int main(void)
{
int a[4], i;
int* p = a;
for(i = 0; i < 4; i++)
{
*p++ = i;
printf("%d", a[i]);
}
return 0;
}
C arrays decay into pointers in some circunstances, but they aren't pointers. Use p instead of a.
It works when you dynamically allocate a because malloc() returns a pointer, not an array.
you should know the differences between array and pointer.I suggest .
In function,the array you put in will turn to pointer(point to first element of array),it's a variable of pointer,so you can do increasement,in main,a is a address of first element,it's constant,so you can't change.you should change pointer p.
In functions you'r passing the array address point to a pointer. and pointer is accessing each variable when u increment it. this is called a walking pointer.
but in case when u use it in main you'r assuming that array is a simple . Think of an array declared by compiler like
int *const array;
so when you try to increment it. it pops an error. so use one more Walking pointer inside
main so u traverse the array
I'm getting gcc errors when I compile my code. The errors are about "passing argument 1 of ‘print_path’ makes pointer from integer without a cast".
Here is my function prototype:
void print_path(int previous[], int desired_node_index);
Here is my function:
void print_path(int previous[], int desired_node_index)
{
if( previous[desired_node_index] != -1 )
print_path( previous[desired_node_index] );
printf("-> %d ", previous[desired_node_index]);
}
and here is where I call my function:
print_path(previous, dest_index);
I'm obviously passing it in wrong, or else I'm doing something incorrectly about how to pass an array into a function. Any help?
Thanks guys!
This is obviously a recursive function. Note that print_path() takes 2 parameters: the first is an int array, and the second is an index to a position inside that array.
Calling it:
print_path( previous[desired_node_index] );
is absolutely wrong (unless you have overloaded this function), because it expects 2 parameters and you are only passing it one. What you should be doing is:
print_path( previous, desired_node_index );
What you seem to be missing in this function is an operation to increase/decrease the index variable, else you will always be printing the same position in the array.
Without knowing what is exactly that you are trying to do, there's the possibility that you wanted to do this:
print_path( previous, previous[desired_node_index] );
An obvious error is:
print_path( previous[desired_node_index] );
I'm not sure what you're trying to do, but I guess you want something like:
#include <stdio.h>
void print_path(int *previous, int desired_node_index);
int main(void) {
int dest_index = 2;
int previous[5] = { -1, 0, 1, 2, 3};
print_path(previous, dest_index);
return 0;
}
void print_path(int *previous, int desired_node_index) {
if( previous[desired_node_index] != -1 )
print_path( previous, previous[desired_node_index]);
printf("-> %d ", previous[desired_node_index]);
}
void receive_array(int *temp_arr)
{
int i=0;
do
{
temp_arr[i]=temp_arr[i]+1;
i++;
}
while((char)temp_arr[i]!='\0');
}
here I have made some modifications. The array temp_arr2[] is a buffer array. In my actual program, I printed the array from the main(). Here, for doing the same thing, one need to store back the end result of some computation into temp_arr[].MAX can be a macro or a global variable. In the previous one, I just forgot to edit the lines: temp_arr[i]=temp_arr[i]+1; (my demo sample code) :)
void receive_array(int *temp_arr)
{
int i=0;
int temp_arr2[MAX];
do
{
temp_arr2[i]=temp_arr[i];
i++;
}
while((char)temp_arr[i]!='\0');
}
If you want to pass array to function and return after changing the elements from the function you can see the following example:
You may find the solution at: https://github.com/krishnabhat81/Send-and-return-array-from-function-in-C
#include <stdio.h>
/*
If you want to return a single-dimension array from a function, you would have to
declare a function returning a pointer as in the following example:
*/
int *getRandom(int arr[])
{
static int r[10];
/*Second point to remember is that C does not advocate to return the address of a
local variable to outside of the function so you would have to define the
local variable as static variable.*/
int i;
for ( i = 0; i < 10; ++i)
{
r[i] = arr[i]+1;//rand();
printf( "r[%d] = %d\n", i, r[i]);
}
return r;
}
/* main function to call above defined function */
int main ()
{
/* a pointer to an int */
int *p;
int i;
int arris[10] = {110,22,33,44,5,6,7,8,9,20};
p = getRandom(arris);
for ( i = 0; i < 10; i++ )
{
printf( "*(p + %d) : %d\n", i, *(p + i));
}
return 0;
}
return 0;
}