简体   繁体   English

strcpy 不能与 char arrays 一起正常工作

[英]Strcpy does not work correctly with char arrays

I get the following output when I run the code below:当我运行以下代码时,我得到以下 output:

Matrikel: 01717
Process finished with exit code -1073741571 (0xC00000FD)

Code:代码:

char infos[255];
char matrikelnr[5];

sprintf(matrikelnr, "%d", s->matnr);
size_t n = strlen(matrikelnr);

while (n != 5) {
    memmove(matrikelnr + 1, matrikelnr, 5);
    matrikelnr[0] = '0';
    n = strlen(matrikelnr);
}

printf("Matrikel: %s", matrikelnr);
strcpy(&infos[0], matrikelnr);
printf("DEBUG");

I already tried: strcpy(infos[0], matrikelnr);我已经尝试过: strcpy(infos[0], matrikelnr); and strcpy(infos[0], matrikelnr);strcpy(infos[0], matrikelnr);

The strcpy seems to have a problem. strcpy似乎有问题。 Could you please help me with the solution?你能帮我解决一下吗?

Thanks already!已经谢谢了!

The main problem of your code is that you don't provide enough room for the string-terminating character '\0' .您的代码的主要问题是您没有为字符串终止字符'\0'提供足够的空间。 Each C string needs this to mark the end of the string.每个 C 字符串都需要这个来标记字符串的结尾。 If you need to store strings with 5 characters, the variable needs to provide space for 6 characters.如果需要存储 5 个字符的字符串,则该变量需要为 6 个字符提供空间。

However, your task can be solved much simpler, if you use standard formatting facilities.但是,如果您使用标准格式化工具,您的任务可以更简单地解决。 Change your call of sprintf() like this:像这样更改您对sprintf()的调用:

char matrikelnr[5 + 1];

sprintf(matrikelnr, "%05d", s->matnr);

The '0' is for using zeroes as filling character, and the '5' for a width of (at least) 5 characters. '0'用于使用零作为填充字符, '5'用于(至少)5 个字符的宽度。

I hope that your numbers are never greater than 99999.我希望你的数字永远不会超过 99999。

Please read the documentation for details, and consider to use safer functions like snprintf() .请阅读文档了解详细信息,并考虑使用更安全的函数,如snprintf()

I think, it is almost impossible to tell you exactly what causes the problem with the given code, but I could give you some advice from my experience.我认为,几乎不可能确切地告诉您导致给定代码问题的原因,但我可以根据我的经验给您一些建议。 Some functions in c (eg memmove(), strcpy()) does not have perfect design as their behavior is undefined according to context. c 中的某些函数(例如 memmove()、strcpy())没有完美的设计,因为它们的行为根据上下文未定义。 So first, make sure NULL Bytes are set correctly in your variables(that can cause many problems in c when it comes to char*).所以首先,确保 NULL 字节在您的变量中设置正确(当涉及到 char* 时,这可能会导致 c 出现许多问题)。 I think you don't have null bytes in your char arrays at right place, that causes problem for string functions(function cannot understand when to stop while copying string from one place to another).我认为您的字符 arrays 中没有 null 字节在正确的位置,这会导致字符串函数出现问题(函数无法理解何时停止将字符串从一个地方复制到另一个地方)。 ps.附言。 I mean char* when I say string you know.当我说你知道的字符串时,我的意思是 char*。 This kind of problems also cause "segmentation fault" quite often.这类问题也经常导致“分段错误”。

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

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