anon_swe
anon_swe

Reputation: 9355

Tricky C char pointer issue

So I'm trying to write a function that will take in two pointers to chars and return a new pointer to their concatenation. Here's my 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 to end of start word
  while (*start != '\0') {
    *newArray = *start;
    newArray++;
    start++;
  }
  while (*add != '\0') {
     *newArray = *add; 
     newArray++;
     add++;
  }
  return newArray;
}

Two questions:

1) As of now it compiles but nothing gets printed. I think this is because my append function returns a pointer to the very end of the concatenated characters. Should I create a temporary character pointer and set it to newArray at the very start (so I can just return that)? Otherwise, I have to somehow decrement my pointer until I get back to the start. But there's no value that (like '\0' for the end of a string) that will tell me I'm at the start of the char array...

2) I read that I can't just take sizeof() a char pointer, so I'm not really sure what to pass as my argument to malloc on the first line of my append function. 100 is just a "large enough" magic number which I want to get rid of...

If I could take sizeof() a char pointer, I'd just do:

char *newArray = malloc(sizeof(strlen(start) + strlen(add)) + 1);

Thanks for the help,

bclayman

Upvotes: 0

Views: 164

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126536

1) Yes, you need to save a pointer to the beginning of the allocated memory so that you can return it. Its better to think of that pointer as the "real" pointer and the pointer you increment as you store characters as the temporary, but it really makes no difference -- a pointer is a pointer

2) That is what strlen is for -- it tells you the length of the string. So you want

char *newArray = malloc(strlen(start) + strlen(add) + 1);

no need for sizeof at all.

With all that, you end up 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 to end of start word
  while (*start != '\0')
    *copy++ = *start++;
  while (*add != '\0')
    *copy++ = *add++;
  *copy = 0; // add a final NUL terminator 
  return newArray;
}

Upvotes: 2

Related Questions