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

   return 0;
}

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

4

3 回答 3

3

写作时的主要区别

char* buf;

是它未初始化并且没有分配内存,所以你必须照顾好自己:

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

这称为动态内存分配(与静态分配相反),它允许您在运行时使用或在调用中使用变量更改分配的内存量。另请注意,如果内存量太大,内存分配可能会失败,在这种情况下,返回的指针将为.reallocmallocNULL

从技术上讲,sizeof(char)不需要上述内容,因为 1char的大小始终为 1 字节,但大多数其他数据类型更大并且乘法很重要 -malloc(100)分配 100 字节,malloc(100 * sizeof(int))分配 100 秒所需的内存量int,通常是 32 上的 400 字节位系统,但可能会有所不同。

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);

另一个有用的函数是calloc接受两个参数(第一个:要分配的元素数,第二个:元素的大小(以字节为单位))并将内存初始化为 0。

于 2012-12-15T18:50:15.273 回答
1

I think calloc (or malloc if you don't have calloc) is what you're after.

于 2012-12-15T18:47:19.083 回答
1

buf is an array statically allocated on the stack. For it to be of type char * you need to allocate dynamically the memory. I guess what you want is something like this:

int main()
{
   int n = 56;
   char * buf = NULL;
   buf = malloc(10 * sizeof(char));
   sprintf(buf, "%i", n);
   printf("%s\n", buf);

   // don't forget to free the allocated memory
   free(buf);

   return 0;
}

EDIT: As pointed out by 'Thomas Padron-McCarthy' in the comments, you should not cast the return of malloc(). You will find more info here. You could also remove completely the sizeof(char) as it will always by 1.

于 2012-12-15T18:47:31.893 回答