Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
841 views
in Technique[技术] by (71.8m points)

printf - Store an int in a char* [C]

int main()
{
   int n = 56;
   char buf[10]; //want char* buf instead
   sprintf(buf, "%i", n);
   printf("%s
", buf);

   return 0;
}

This piece of code works, my question is what if i want the same behaviour, with buf being a char* ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The main difference when writing

char* buf;

is that it is uninitialized and no memory is allocated, so you'll have to take care yourself:

char* buf = malloc(10 * sizeof(char));
// ... more code here
free(buf); // don't forget this or you'll get a memory leak

This is called dynamic memory allocation (as opposed to static allocation) and it allows you nice things like changing the amount of allocated memory at runtime using realloc or using a variable in the malloc call. Also note that memory allocation can fail if the amount of memory is too large, in this case the returned pointer will be NULL.

Technically, sizeof(char) above isn't needed because 1 char will always be 1 byte in size, but most other data types are bigger and the multiplication is important - malloc(100) allocates 100 bytes, malloc(100 * sizeof(int)) allocates the amount of memory needed for 100 ints which usually is 400 bytes on 32-bit systems, but can vary.

int amount = calculate_my_memory_needs_function();
int* buf = malloc(amount * sizeof(int));
if (buf == NULL) {
  // oops!
}
// ...
if (more_memory_needed_suddenly) {
   amount *= 2; // we just double it
   buf = realloc(buf, amount * sizeof(int));
   if (!buf) { // Another way to check for NULL
     // oops again!
   }
}
// ...
free(buf);

Another useful function is calloc that takes two parameters (first: number of elements to allocate, second: size of an element in bytes) and initializes the memory to 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...