Hello,
I started programming in c a while ago. And to understand things better, i made a my own string appender (append b to a). I got version 1.0 working:
Code:
char * append(char * dest, char * src)
{
char * buffer = malloc(strlen(dest) + strlen(src) + 1);
unsigned int i = 0;
unsigned int x = 0;
for(; dest[i] != '\0'; i++) buffer[i] = dest[i];
x = i;
for(; src[i-x] != '\0'; i++) buffer[i] = src[i-x];
buffer[i] = '\0';
return buffer;
}
but version 2.0, where i give the adres of the buffer in the header (so x = append(a, b) can be replaced with append(a, b)), is not working.. it gives me a sig fault.. and i can't find where it goes wrong with my memory..:
I tried this:
Code:
void append(char ** buffer, char * src)
{
int i;
for(i = 0; i <= strlen(src); i++) buffer[i] = &src[i];
}
and this..
Code:
void append(char ** buffer, char * src)
{
int i;
for(i = 0; i <= strlen(src); i++) *buffer[i] = src[i];
}
The function call in my main function looks like this:
Code:
int main()
{
char * str1 = "Hello";
char * buffer = malloc(strlen(str1) + 1);
append(&buffer, str1);
printf("%s", buffer);
free(buffer);
return 0;
}
Can anyone tell me where, and why it goes wrong, and maby even try to explain how to fix?
Thanks in advance!