简体   繁体   中英

how to convert a value to integer type string?

we all know that to convert a value in a string we can do following

char* buffer = ... allocate a buffer ...
int value = 4564;
sprintf(buffer, "%d", value);

but what can we do if instead of character buffer i want to convert data to integer buffer, basically i want to do following

int* buffer = ... allocate a buffer ...
int value = 4564;
sprintf(buffer, "%d", value);

Thanks in advance

Be sure to define buffer as the value of 'value', and not a pointer to the address of 'value'. See below:

#include <stdlib.h>
#include <stdio.h>
#include <memory.h>

int main(int argc, char** argv)
{
    /* Allocate memory. */
    int* buffer = malloc(sizeof(int));

    int value = 1000;

    /* Sets the number stored in buffer equal to value. */
    *buffer = value;

    /* prints 1000 */
    printf("%d\n", *buffer);

    /* Change value to show buffer is not pointing to the address of 'value'. */
    value = 500;

    /* Still prints 1000. If we had used 
    int* buffer = &value, it would print 500. */
    printf("%d\n", *buffer);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM