0

given a pointer to unsigned char value, *ptr.

How to copy its whole value to new char value char buff; in a correct way (malloc etc), without looping for each character? Any way to retreive the memory amount currently allocated for the pointer value?

dmckee --- ex-moderator kitten
  • 98,632
  • 24
  • 142
  • 234
kagali-san
  • 2,964
  • 7
  • 48
  • 87

2 Answers2

2

If you really have a single character:

char buff = (char)*ptr;

If you have a string which i assume as you are talking about looping over characters:

char *buff = strdup(ptr);
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 2
    Keeping in mind that `strdup` is not ISO C. If your implementation doesn't have one, you can find one here: http://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c/252802#252802 – paxdiablo Nov 20 '10 at 12:28
1

Any way to retreive the memory amount currently allocated for the pointer value?

Not in the sense you're looking for, no.

In the language sense, the amount of memory allocated for the pointer value (in question) is, of course, sizeof(unsigned char *). This (again, of course) does in no way correlate with the size of the memory block the pointer is pointing to. A pointer simply holds no such information.

If you (for some reason) cannot pass the size information alongside with the pointer, you must decide a value of unsigned char to signify the end of the memory block (and assign that value to the end of the memory block). (This is how strings work in C). The only way to find the length of the block is to loop through the values.

Why do you have a pointer to unsigned char, if it really points to char? By the way, char buff is hardly a buffer, as it only holds a single value of char.

eq-
  • 9,986
  • 36
  • 38