gpt4 book ai didi

C Concat String Int Sprintf

转载 作者:行者123 更新时间:2023-11-30 19:09:09 25 4
gpt4 key购买 nike

为什么第二个 sprintf 不工作?

char* jc;
char* tn;
char* result = malloc((256)*sizeof(char));
int thread=99;
int jobcounter=88;
sprintf(jc, "%d", jobcounter);
sprintf(tn, "%d", thread);
strcpy(result,"file_");
strcat(result,jc);
strcat(result,"_");
strcat(result, tn);
strcat(result,".html");
printf("%s",result);

输出:

file_88_Þ*m.html

最佳答案

就你的情况

sprintf(jc, "%d", jobcounter);
sprintf(tn, "%d", thread);

原因undefined behavior因为这些指针(第一个参数)都不指向任何有效内存。

您需要确保用于访问内存位置的指针指向有效的内存。您可以

  • 使它们指向静态/自动分配的变量或
  • 使用内存分配器函数,如 malloc() 或系列。

关于C Concat String Int Sprintf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43685228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com