mw****@freenet.de wrote:
Hi!,
im trying to copy the middle part of a dinamycally created char* string
with memcopy but all i get is rubbish...
I understand, that malloc can allocate memory wherever it wants and it
does not have to be in one piece... but how do i access higher parts of
the allocated memory?
lets say source contains "helloworld" and i only want to have "llowo"
in destination... what do i do?
char* destination=malloc(5);
Obviously wrong. There are 6 chars in "llowo".
char* source=malloc(8);
Obviously wrong. There are 11 chars in "helloworld".
[.....]
memcpy(destination, source +3 ,5);
Obviously wrong. The chars {'l','l','o','w','o'} begin at source+2.
>
this line copies whatever.... and writing source[3] does not work
either... a hint would be nice... :D
"Does not work" doesn't work as a description. Below you will see a
demonstration that everything you claim "does not work" does work when
done correctly.
Are you perhaps trying to use the non-string array
{'l','l','o','w','o'} as if it were a string?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char source[] = "helloworld";
char *dest;
size_t i;
printf("Copying the 5 chars from \"%s\"[2]\n", source);
if (!(dest = malloc(5))) {
printf("malloc failed.\n");
exit(EXIT_FAILURE);
}
memcpy(dest, source + 2, 5);
for (i = 0; i < 5; i++)
printf("%u %#3o %c\n", (unsigned) i, (unsigned) dest[i],
dest[i]);
putchar('\n');
free(dest);
printf("Creating a string using the 5 chars from \"%s\"[2]\n",
source);
if (!(dest = malloc(6))) {
printf("malloc failed.\n");
exit(EXIT_FAILURE);
}
memcpy(dest, source + 2, 5);
dest[5] = 0;
for (i = 0; i < 6; i++) {
if (dest[i])
printf("%u %#3o %c\n", (unsigned) i, (unsigned) dest[i],
dest[i]);
else
printf("%u %#3o %s\n", (unsigned) i, (unsigned) dest[i],
"(zero byte)");
}
printf("The created string: \"%s\"\n", dest);
free(dest);
return 0;
}
Copying the 5 chars from "helloworld"[2]
0 0154 l
1 0154 l
2 0157 o
3 0167 w
4 0157 o
Creating a string using the 5 chars from "helloworld"[2]
0 0154 l
1 0154 l
2 0157 o
3 0167 w
4 0157 o
5 0 (zero byte)
The created string: "llowo"