I'm trying declare a string in ANSI C and am not sure of the best way to do it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
char *InitStr(char *ReturnStr){
ReturnStr = NULL;
ReturnStr = realloc( ReturnStr, strlen("") +1 );
strcpy( ReturnStr , "");
return ReturnStr;
}
char *AddStr(char *StrObj1,char *StrObj2){
StrObj1 = realloc(StrObj1,(strlen(StrObj1) + strlen(StrObj2)+1));
strcat(StrObj1, StrObj2);
return StrObj1 ;
}
char *JoinStr(const char *fmt, ...) {
char *p = NULL;
size_t size = 30;
int n = 0;
va_list ap;
if((p = malloc(size)) == NULL)
return NULL;
while(1) {
va_start(ap, fmt);
n = vsnprintf(p, size, fmt, ap);
va_end(ap);
if(n > -1 && n < size)
return p;
// failed: have to try again, alloc more mem.
if(n > -1) // glibc 2.1
size = n + 1;
else //* glibc 2.0
size *= 2; // twice the old size
if((p = realloc (p, size)) == NULL)
return NULL;
}
}
main(){
printf("\n");
char *MyLocalString = InitStr(MyLocalString);
printf("InitStr: %s\n",MyLocalString);
printf("---------------------------------------------------\n");
AddStr(MyLocalString ,"Hello String!");
printf("1. AddStr: %s\n",MyLocalString);
printf("---------------------------------------------------\n");
AddStr(MyLocalString ,"\n\tAdd more string 1");
printf("2. AddStr: %s\n",MyLocalString);
printf("---------------------------------------------------\n");
AddStr(MyLocalString ,"\n\tAdd more string 2");
printf("3. AddStr: %s\n",MyLocalString);
printf("---------------------------------------------------\n");
//MyLocalString = AddStr(MyLocalString ,"\n Add more string");
MyLocalString = AddStr(MyLocalString ,JoinStr("%s%s%s", "\n\tString3", "\n\tString2", "\n\tString3"));
printf("4. JoinStr: %s\n",MyLocalString);
printf("---------------------------------------------------\n");
printf("\n");
}
In this code I have 3 functions to handle the string:
InitStr
- to initial stringAddStr
- to add stringJoinStr
-to Join string
The code works fine, however, I am not sure if this is a decent way of handling a string since I am using pointers.
char* EmptyStr(void){ return strdup(""); }
– Jim Balter Jun 9 '12 at 23:34