T
tano
Hello,
I have to insert a char in the middle of a string, I have written two functions
but I don't know what is the better? The problem is: if I use malloc() I copy
all the string with the new char in the middle every time, with realloc() the
part of the string before the position where the char has to be inserted is not
changed if realloc returns the same pointer is passed, but if not the
string is copied at all the first time, and then the part after the char has to
be shifted to right.. Perhaps it could be possible to make another function
using the system call of the os (brk, sbrk)?
Can anybody give me suggestions or clarify my ideas?
Thanks,
tano
/* Code: the len is in memory, incremented after every insertion, so it
doesn't need to compute it using strlen() */
#include <stdio.h>
#include <stdlib.h>
char* insert_char_malloc (char *str, int len, char c, int pos)
{
char *p;
int i;
p = malloc(len + 2);
for (i = 0 ; i < pos ; ++i)
p = str;
p[i++] = c;
for ( ; i < len + 2 ; ++i)
p = str[i - 1];
free(str);
return p;
}
char* insert_char_realloc (char *str, int len, char c, int pos)
{
int i;
str = realloc(str, len + 2);
for (i = len + 1 ; i > pos ; --i)
str = str[i - 1];
str = c;
return str;
}
I have to insert a char in the middle of a string, I have written two functions
but I don't know what is the better? The problem is: if I use malloc() I copy
all the string with the new char in the middle every time, with realloc() the
part of the string before the position where the char has to be inserted is not
changed if realloc returns the same pointer is passed, but if not the
string is copied at all the first time, and then the part after the char has to
be shifted to right.. Perhaps it could be possible to make another function
using the system call of the os (brk, sbrk)?
Can anybody give me suggestions or clarify my ideas?
Thanks,
tano
/* Code: the len is in memory, incremented after every insertion, so it
doesn't need to compute it using strlen() */
#include <stdio.h>
#include <stdlib.h>
char* insert_char_malloc (char *str, int len, char c, int pos)
{
char *p;
int i;
p = malloc(len + 2);
for (i = 0 ; i < pos ; ++i)
p = str;
p[i++] = c;
for ( ; i < len + 2 ; ++i)
p = str[i - 1];
free(str);
return p;
}
char* insert_char_realloc (char *str, int len, char c, int pos)
{
int i;
str = realloc(str, len + 2);
for (i = len + 1 ; i > pos ; --i)
str = str[i - 1];
str = c;
return str;
}