Hi I would like to create a function that appends a character to a character array.. this is what I have got so far..

char * appendCharToCharArray(char * array, char a)
{    
     char * ret = (char*)malloc(sizeof(array) + 1 + 1);
       strcpy(ret,array);
         ret[strlen(ret)] = a;
         ret[sizeof(ret)] = '\0';
     return ret;     
}

this seems to work but only for up to 4 letter words somehow.

I thought maybe I could do it using a string object to concatenate and then returning it as a characted array using stringobject.c_str(); but I would prefer not to do this unless I have to.

Any help is greatly appreciated.

Thanks.

Recommended Answers

All 7 Replies

>this seems to work but only for up to 4 letter words somehow.
It seems the size of a pointer is four bytes on your system.

>char * ret = (char*)malloc(sizeof(array) + 1 + 1);
sizeof doesn't do what you want here. It's giving you the size of a pointer, not the length of the string. If you want the length of the string, use strlen. And you really should be using new instead of malloc.

char * appendCharToCharArray(char * array, char a)
{    
     char * ret = new char(strlen(array) + 1 + 1); // + 1 char + 1 for null;
       strcpy(ret,array);
         ret[strlen(ret)] = a;
         ret[sizeof(ret)] = '\0';
     return ret;     
}

ok I have made the changes, used new char instead of malloc and used strlen instead of sizeof, but the same thing happens.

What sort of thing would I have to consider doing to get what I need.. maybe..

>convert char a to a string "a\0"
>use strcat() to concatenate strings
>return string value

>but the same thing happens.
Okaaay, you clearly don't know what you're doing, so I think an example is in order:

#include <cstring>

char *append_char ( const char *s, const char c )
{
  std::size_t len = std::strlen ( s );
  char *ret = new char[len + 2];

  std::strcpy ( ret, s );
  ret[len] = c;
  ret[len + 1] = '\0';

  return ret;
}

A common solution to this problem is to pass around the array size along with the array. That way, it would work for all types of arrays, not just C style strings (char arrays with terminating null character).

void doSomething(int* arr, int size)
{
     //get ready to add some bugs to your code
}
commented: Fine post, you're also a good teacher +2
Member Avatar for iamthwee

>but I would prefer not to do this unless I have to?

Er why not?

char *s;
s=(char*)malloc(10);
cin>>s;
while(*s!='\0'){++s;}
*s='p';
++s;
*s='\0';
--s;
while(*s!='\0'){--s;}
++s;
cout<<s;

That is some pretty bad to code to resurrect a 5 year old thread with.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.