質問

I am writing to a pointer using C's sprintf function.

I write blank characters (spaces), commas, and integers to this pointer. The pointer has an allocation of 4096 bytes.

I increment the pointer manually as I write however I am running into issues when I format.

Here is the code:

sprintf(result, "%d ", number);
memory += 3;

sprintf(result, "%d, ", number);
memory += 4;

OUTPUT: printf("%s", (char *)memory);

Depending on what's going on the program I do one of the following above. Initially I used 2 and 3 respectively but that led to formatting issues with way of spacing when I output. I checked online and found that integers take 2 bytes of memory and char's take 1 byte, hence my change to 3 and 4 respectively. (space (1) + integer(2)) = 3 and (space (1) + comma (1) + integer (2)) = 4. However when I use these I lose some of my data on output- it appears it cuts it short. Again, I have allocated 4096 bytes to the pointer and that should be plenty to output correctly.

Perhaps I'm incrementing my pointer incorrectly or printing it out incorrectly?

役に立ちましたか?

解決

It's not entirely clear what you are doing here, but I assume you are trying to adjust the write pointer in your output buffer according to the number of characters taken by the sprintf calls.

sprintf returns the number of characters actually written into the output buffer, so instead of incrementing your pointer by a guessed number of characters, use the return value.

numWritten = sprintf(result, "%d ", number);
memory += numWritten;

I assume that memory is a char*; you would also get unexpected results if it was a pointer to some other type because the arithmetic is affected by what the pointer is pointing to.

他のヒント

The thing is you are converting integer to string. Each of integer's digit will consume one byte (sizeof(char)).

int number = 1;
sprintf(result, "%d ", number);
>> "1 " -> two bytes
int number = 134;
sprintf(result, "%d ", number);
>> "134 " -> four bytes

To fix this you should calculate digits in the number and add it to the memory pointer.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top