Reputation: 1690
i have a doubt with passing array as a argument to function, my code as below,
#include <stdio.h>
#include <string.h>
void str_cpy(char a[], char b[])
{
a = b;
printf("%s\n", a);
}
int main()
{
char a[] = "hello";
char b[] = "world";
str_cpy(a, b);
printf ("%s\n", a);
return 0;
}
In the above code i am passing array to function is pass by reference so it should print "world" in the main function because i am assigning value of b to a i.e a = b in the function definition but it is not , so please help me ..
Upvotes: 1
Views: 1183
Reputation: 206518
When you pass an array to function. It decays as an pointer to the first element of the array.
Your function str_cpy()
only points the passed pointer a
to another pointer b
. It does not modify the contents of the original character array a
. Note the pointers a
and b
are local to the function.
Also, note that basic rule about arrays is:
"Arrays are not assignable, You have to copy each element in array."
The code you have is equivalent to:
char a[] = "hello";
char b[] = "world";
char *ptr1 = a;
char *ptr2 = b;
ptr1 = ptr2;
printf("[%s]",a);
It does not change the contents of the original array, it merely points an pointer which was pointing to the array to some another array.
Copying each element of one array to another array is the functionality that strcpy() provides. You should simply use the standard library provided function.
Upvotes: 3
Reputation: 9204
You are interpreting it as wrong, It's actually pass by value
.
void str_cpy(char a[], char b[]) // it's same as str_cpy(char *a,char *b)
{
a = b;
printf("%s\n", a); // here it will print "world" because it's a local
// change in a but actually in main a still contains "hello"
}
Since you are using <string.h>
you can directly use strcpy(a,b);
Or, try something like this to copy char by char into target array.
str_cpy(char *a,char *b)
{
while(*b != '\0')
{
*a=*b;
a++;
b++;
}
}
But it could be a problem if array a
doesn't have enough space to keep the copied character.
Upvotes: 1
Reputation: 753605
Your str_cpy()
function could be written as:
void str_cpy(char *a, char *b)
{
a = b;
printf("%s\n", a);
}
This is semantically equivalent to what you wrote; there is no operational difference between what you wrote and what I wrote. The arrays are passed as pointers to the first elements of the array. They are conveniently initialized local pointer variables. Within the scope of the function, you make a
point to the same place that b
does, but this doesn't affect the arrays in the main()
program.
To copy arrays around in C, you have to copy each element in turn:
void str_cpy(char *a, char *b)
{
while ((*a++ = *b++) != '\0')
;
printf("%s\n", a);
}
Upvotes: 1