Reputation: 129
i am trying to write a program that takes a string and copies that string to another char array using the concept of call by reference,but my program seems to be outputing the first character only
#include <stdio.h>
#include <conio.h>
void copy(char *[]);
void main()
{
char a[10];
printf("\t\tPROGRAM TO COPY STRING USING FUNCTION AND POINTER");
printf("\n\t\t--------------------------------------------");
printf("\nEnter the string :");
gets(a);
copy(&a);
getch();
}
void copy(char *p[]){
int i=0;
char b[10];
while(*p!='\0'){
b[i]=*p++;
i++;
}
b[i]='\0';
printf("\nThe string after copying is %s",b);
}
Upvotes: 1
Views: 528
Reputation: 239
&a will give a pointer to pointer not the pointer to first element of the array
a will give you the pointer to the first element to the array
so inorder to copy the string you should pass the pointer to the first element to the array and receive only the char pointer in the function than the copy should work
Upvotes: 0
Reputation: 3001
When you pass a pointer to array, you don't need this []
. This seems like you are passing an array of pointers. Try:
#include <stdio.h>
#include <conio.h>
void copy(char* p);
void main()
{
char a[10];
printf("\t\tPROGRAM TO COPY STRING USING FUNCTION AND POINTER");
printf("\n\t\t--------------------------------------------");
printf("\nEnter the string :");
fgets(a, 10, stdin);
copy(a);
getch();
}
void copy(char* p){
int i=0;
char b[10];
while(*p!='\0'){
b[i]=*p++;
i++;
}
b[i]='\0';
printf("\nThe string after copying is %s",b);
}
Because you want to pass an array, with only one pointer, which points to the first char. Then you iterate over thic array with incrementing the pointer getting the next char in the array.
Furthermore you should not use gets
. Use isntead fgets
. And what I forgot, you don't have to pass the address of your array (&a
), because a points directly to this value, so you can pass a
directly.
Upvotes: 1