Monday, July 27, 2009

How do u implement string functions using pointers in C?

i need a sample program involving strcpy n strcat

How do u implement string functions using pointers in C?
#include %26lt;stdio.h%26gt;


#include %26lt;string.h%26gt;





main() {


char* a = "hello ";//a is a pointer to a string "hello "


char* b = "world";//b is a pointer to a string "world"


char string1[strlen(a)+strlen(b)+1];//string1 is a pointer to a string of characters





strcpy(string1, a);//string1 now cantains a "hello " string


printf("%s\n", string1);





strcat(string1, b);//string1 now cantains hello world


printf("%s\n", string1);


}
Reply:The code example by jericbryledy is incorrect because no space has been allocated for string1 to contain the copied characters.





use malloc to provide space for the copied characters.





string1 = (char *)malloc(sizeof(char) * (strlen(a) + 1));


strcpy(string1, a);


No comments:

Post a Comment