Tricky C char pointer issue -
so i'm trying write function take in 2 pointers chars , return new pointer concatenation. here's attempt:
#include <stdio.h> #include <stdlib.h> char * append (char *, char *); int main(void) { char *start = "start"; char *add = "add"; char* newstring = append(start, add); printf("%s\n", newstring); return 0; } char * append(char *start, char *add) { char *newarray = malloc(sizeof(char) * 100); //get end of start word while (*start != '\0') { *newarray = *start; newarray++; start++; } while (*add != '\0') { *newarray = *add; newarray++; add++; } return newarray; }
two questions:
1) of compiles nothing gets printed. think because append function returns pointer end of concatenated characters. should create temporary character pointer , set newarray @ start (so can return that)? otherwise, have somehow decrement pointer until start. there's no value (like '\0' end of string) tell me i'm @ start of char array...
2) read can't take sizeof() char pointer, i'm not sure pass argument malloc on first line of append function. 100 "large enough" magic number want rid of...
if could take sizeof() char pointer, i'd do:
char *newarray = malloc(sizeof(strlen(start) + strlen(add)) + 1);
thanks help,
bclayman
1) yes, need save pointer beginning of allocated memory can return it. better think of pointer "real" pointer , pointer increment store characters temporary, makes no difference -- pointer pointer
2) strlen
-- tells length of string. want
char *newarray = malloc(strlen(start) + strlen(add) + 1);
no need sizeof
@ all.
with that, end with:
char *append(char *start, char *add) { char *newarray = malloc(strlen(start) + strlen(add) + 1); if (!newarray) return 0; // out of memory char *copy = newarray; //get end of start word while (*start != '\0') *copy++ = *start++; while (*add != '\0') *copy++ = *add++; *copy = 0; // add final nul terminator return newarray; }
Comments
Post a Comment