Write a C program to copy string using pointers.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char source[256], *dest;
int i, len;
/* get the input string from the user */
printf("Enter your input string:");
fgets(source, 256, stdin);
source[strlen(source) - 1] = '\0';
/* find the length of the given input string */
len = strlen(source);
/* dynamically allocate memory for dest string */
dest = (char *) malloc(sizeof(char) * len);
/* copy characters in souce string to dest string */
for (i = 0; i <= len; i++) {
*(dest + i) = *(source + i);
}
/* print the results */
printf("Result:");
printf("\nSource String : %s", source);
printf("\nDestination String: %s\n", dest);
return 0;
}
#include <string.h>
#include <stdlib.h>
int main() {
char source[256], *dest;
int i, len;
/* get the input string from the user */
printf("Enter your input string:");
fgets(source, 256, stdin);
source[strlen(source) - 1] = '\0';
/* find the length of the given input string */
len = strlen(source);
/* dynamically allocate memory for dest string */
dest = (char *) malloc(sizeof(char) * len);
/* copy characters in souce string to dest string */
for (i = 0; i <= len; i++) {
*(dest + i) = *(source + i);
}
/* print the results */
printf("Result:");
printf("\nSource String : %s", source);
printf("\nDestination String: %s\n", dest);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your input string:strcpy
Result:
Source String : strcpy
Destination String: strcpy
Enter your input string:strcpy
Result:
Source String : strcpy
Destination String: strcpy
No comments:
Post a Comment