you use 'pass by reference' with large arrays or structures
and use the & symbol (for the address of the item )
so you pass just 1,2,4 or 8 bytes or so (depending on datatype)
eg
Hi, dickie bird I think you got it wrong when passing a char array by reference, here is a small program to show the difference between passing int values and arrays by reference compared to by value....not the use of the ampersand ( & ) in the call to refer_check function and the use of the pointer symbol ( * ) in the function and in the prototype and definition.
#include <stdio.h>
#include <string.h>
void refer_check(char *array, int *num);
void value_check(char array[], int num);
int main(void)
{
char arrayname[50];
int number = 1;
strcpy(arrayname,"Lets Start In Main"
printf("\nString in main before is %s", arrayname);
printf("\nNumber in main before is %d", number);
refer_check(arrayname, &number);
printf("\n\nString in main after reference function is %s (changed)", arrayname);
printf("\nNumber in main after reference function is %d (changed)", number);
value_check(arrayname, number);
printf("\n\nString in main after value Function is %s (changed)", arrayname);
printf("\nNumber in main after value Function is %d (not changed)", number);
return 0;
}
void refer_check(char *array, int *num)
{
strcpy(array, "Refence Function"
printf("\n\nString in the reference function is %s", array);
*num = 10;
printf("\nNumber in the reference function is %d", *num);
}
void value_check(char array[], int num)
{
strcpy(array, "Value Function"
printf("\n\nString in the value function is %s", array);
num = 20;
printf("\nNumber in the value function is %d", num);
}
you can see how the values change if you compile and run this.
I have another question: In a void function, I want to do some error checks, if the condition is failed, exit the function. I use 'return 0' to exit function but it give me the warning. I guess return 0 only works for non-void function.
In VB if I want to exit a function, I use exit sub. What syntax to exit a void function in C?
Note that there really is no pass by reference in C. You can change automatic variables in the caller's function by using pointers (as demonstrated above), however you are still passing everything by value.
The reason that I mention this is because describing this mechanism as "pass by reference" can be confusing to newcomers. In particular, I suspect it is one of the causes of this common mistake:
void foo(char *s)
{
s=malloc(500);
}
int main(void)
{
char *s;
foo(s);
/* Hey, why doesn't s point at allocated memory?? */
return 0;
}
s is passed by value, so the s in main() is a different pointer than the s in foo().
Russ
bobbitts@hotmail.com
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.