Hi, can anyone explain to me why is that when i pass an ARRAY from the Main to a function, and let the function change the value of the array, the array inside main CHANGES.
On the other hand, when i do the same with INTEGERS, the values inside the main function don't change. Here is a short sample code, please HELP!!! Thanks!
#include %26lt;stdio.h%26gt;
#include %26lt;stdlib.h%26gt;
#include %26lt;string.h%26gt;
int func(char arrdbl[5][100], int a, int b)
{
a--;
b--;
printf("a and b values are: %d, %d\n",a,b); // 4 and 9
strcat(arrdbl[0], "Apple");
printf("arrdbl[0]: %s \n",arrdbl[0]); //AaApple
return 0;
}
int main(void)
{
int a = 5;
int b = 10;
char arrdbl[5][100] = {"Aa", "Bb", "Cc", "Dd", "Elephant"};
func(arrdbl,a,b);
printf("a and b values After are: %d, %d\n",a,b); // back to 5 and 10
printf("arrdbl[0] After: %s \n",arrdbl[0]); //AaApple is retained. Why doesn't it work for ints???
system("PAUSE");
return 0;
}
Changing Values of passed paramters in C?
It works for array because array name is actually a reference to the location containing your value and it doesnot work for ints because you are passing the values of int.
In order to make it work for int pass a reference to location containing your integer value.
i.e check out the code
int func(char arrdbl[5][100],int *a, int *b)
{
*a--; // the contents of a are decremented
*b--;
printf("a and b values are: %d, %d\n",*a,*b); // 4 and 9
strcat(arrdbl[0], "Apple");
printf("arrdbl[0]: %s \n",arrdbl[0]);//AaApple
return 0;
}
int main(void)
{
int a = 5;
int b = 10;
char arrdbl[5][100] = {"Aa", "Bb", "Cc", "Dd", "Elephant"};
func(arrdbl,%26amp;a,%26amp;b); // %26amp; passes the address of location containing value of a and b.
printf("a and b values After are: %d, %d\n",a,b);
printf("arrdbl[0] After: %s \n",arrdbl[0]);
system("PAUSE");
return 0;
}
Reply:An array is actually a pointer to a specific place in memory (the beginning of the array). If you pass that pointer, it's still going to be pointing to the same chunk of memory. If you don't want the original array to be changed, what you want to do, is create a new array, copy the contents of the original array into the new one, and then pass the new array to your function.
Reply:The integers are not changed because you passed them by value. But when you pass an array to a function, you're automatically passing a pointer. So when you use strcat on arrdbl[0], you're actually modifying the original memory. The a and b that you subtract 1 from are just copies of the originals.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment