将int存储在char * [C]中

时间:2012-12-15 18:45:34

标签: c printf

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

   return 0;
}

这段代码有效,我的问题是如果我想要相同的行为,buf是char *?

3 个答案:

答案 0 :(得分: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

这称为dynamic memory allocation(与静态分配相对),它允许您使用realloc或使用malloc调用中的变量等changing the amount of allocated memory at runtime等优秀内容。 另请注意,如果内存量太大,内存分配可能会失败,在这种情况下返回的指针将为NULL

从技术上讲,上面不需要sizeof(char),因为1 char的大小总是1个字节,但大多数其他数据类型更大,乘法很重要 - malloc(100)分配100 bytes 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。

答案 1 :(得分:1)

我认为calloc(或malloc,如果你没有calloc)是你所追求的。

答案 2 :(得分:1)

buf是在堆栈上静态分配的数组。要使其为char *类型,您需要动态分配内存。我想你想要的是这样的:

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;
}
编辑:正如“托马斯·帕德龙 - 麦卡锡”在评论中所指出的那样,你不应该归还malloc()。您会找到更多信息here。您也可以完全删除sizeof(char) 1,因为{{1}}。

相关问题