Hi,
I trying to append something in a char pointer array but coudn't able.. can anyone please help me?
Example:
char* a = "World";
now i want to add "hello" before the "World" in the variable a.
Hi,
I trying to append something in a char pointer array but coudn't able.. can anyone please help me?
Example:
char* a = "World";
now i want to add "hello" before the "World" in the variable a.
You can't, without invoking undefined behaviour. In your example, "World" is a constant string, so cannot be modified.
Declare an array long enough to contain all the data you need, and modify it accordingly.
This is one case where a pointer does not behave like an array.Code:#include <string.h> int main() { char a[12] = "World"; /* 12 = strlen("Hello World") + 1 */ strcpy(a, "Hello World"); /* Copy "Hello World" into the array a */ }
If you want to append character to a char * you need to allocate memory for that .
Code:#include<stdio.h> #include<string.h> #include<malloc.h> main() { char *a="Hello "; char *b="World"; char *c = malloc(strlen(a)+strlen(b)+1); strcat(c,a); strcat(c,b); printf("%s\n",c); }
There are a number of problems with karthigayan's example, among them:Originally Posted by apus29
- <stdlib.h> should be included instead of <malloc.h>
- Although c points to sufficient memory, it does not actually point to the first character of a string as the dynamic array is left uninitialised.
- There is no corresponding free() to the malloc().
- a and b should be declared as points to const char.
- The main function should be declared as returning int
- Unless you are compiling with respect to C99, the main function should return a value, usually 0.
- The code is severely in need of proper indention.
You might want to try:
Code:#include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { const char *a = "Hello "; const char *b = "World"; char *c = malloc(strlen(a) + strlen(b) + 1); c[0] = '\0'; strcat(c, a); strcat(c, b); printf("%s\n", c); free(c); return 0; }
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Thanks laserlight.. for your informational reply..
I had to add <stdlib.h> to run the program and i also freed the memory too..
what i did is here...
and its giving my desired answer (to modify the variable 'a').please correct me if there is anything wrong.Code:#include<stdio.h> #include<conio.h> #include<string.h> #include <stdlib.h> int main() { char *a="Hello "; char *b="World"; char *c = (char*)malloc(strlen(a) + strlen(b) + 1); strcpy(c,a); //use strcpy to avoid the garbage value strcat(c,b); a = c; int i; for(i = 0; i < strlen(a); i++) printf("%c", *(a+i)); free (c); return 0; }