简体   繁体   English

未初始化的值使用,使用 sprintf 或 strcat 时出错

[英]uninitialized value usage, error while using sprintf or strcat

The piece of code given below works completely fine on my IDE.下面给出的代码在我的 IDE 上完全可以正常工作。 But when I submit this on codeforces , I get an error pointing at the sprintf line.但是当我在codeforces上提交这个时,我收到一个指向sprintf行的错误。

Probably, the solution is executed with error 'uninitialized value usage'可能,解决方案执行时出现错误“未初始化的值使用”

I used sprintf instead of strcat to concatenate two arrays as suggested from a stackoverflow answer.我使用 sprintf 而不是strcat来连接两个 arrays ,如stackoverflow答案所建议的那样。 But it gives me the same error.但它给了我同样的错误。

char a[101],b[101],c[201],d[300];
fgets(a,101,stdin);
fgets(b,101,stdin);
fgets(c,201,stdin);
// strcat(d,a);
sprintf(d, "%s%s",d,a);

You are writing the uninitialized variable d to the location d .您正在将未初始化的变量d写入位置d That doesn't make any sense.这没有任何意义。 Perhaps you meant to do sprintf(d,"%s",a);也许你打算做sprintf(d,"%s",a); ? ?

In that case you don't need to initialize d , but if you use strcat you must initialize the first item in d to \0 .在这种情况下,您不需要初始化d ,但如果您使用strcat ,则必须将d中的第一项初始化为\0

You can only use strcat() if you've already initialized both strings.如果您已经初始化了两个字符串,则只能使用strcat()

Since you haven't put anything into d yet, you don't need to concatenate to it.由于您尚未将任何内容放入d中,因此您无需连接到它。 Just copy the contents of a to it with strcpy() .只需使用strcpy()a的内容复制到其中即可。

strcpy(d, a);

Also, even if you have initialized d, you can't use另外,即使你已经初始化了d,你也不能使用

sprintf(d, "%s%s",d,a);

It's not valid to use the same string as the destination of sprintf() if it's also one of the source strings.如果它也是源字符串之一,则使用与sprintf()的目标相同的字符串是无效的。

You have not initialized d so it probable has no '\0' character.您尚未初始化 d ,因此它可能没有 '\0' 字符。

strcat searches for the first 0 in the array and then starts concatenting from there. strcat 搜索数组中的第一个 0,然后从那里开始连接。 If it cant find a 0 it read past the end of the array.如果它找不到 0,它会读取数组末尾的内容。

char d[300] = {0};

would fix it both for strcat and sprintf将为 strcat 和 sprintf 修复它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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