gpt4 book ai didi

c - 我的一行 strncpy : while(*s++ = *t++ && n--> 0);? 有什么问题

转载 作者:太空宇宙 更新时间:2023-11-04 00:30:43 25 4
gpt4 key购买 nike

#include <stdio.h>
#define STR_BUF 10000
#define STR_MATCH 7

void mystrncpy(char* s, char* t, int n) {
while(*s++ = *t++ && n-- > 0);
}

int main() {
int result;
char str_s[STR_BUF] = "not so long test string";
char buf_1[STR_BUF];
mystrncpy(buf_1, str_s, STR_MATCH);
printf ("buf_1 (mystrncpy, 7 chars): %s\n", buf_1);
return 0;
}

当我运行它时,没有任何反应

ian@ubuntu:~/tmp$ gcc myncpy.c -o myn&&./myn
buf_1 (mystrncpy, 7chars):

最佳答案

赋值的优先级低于 &&,因此您的 while 条件等同于:

while (*s++ = (*t++ && n-- > 0))

*s++10 进行比较。那不是你想要的。

while ((*s++ = *t++) && n-- > 0)

应该修复它。

请注意,您仍然通过使用 %s 打印字符串来调用未定义的行为。它没有以 null 结尾。

char buf_1[STR_BUF] = "";

是解决这个问题的一种方法。

关于c - 我的一行 strncpy : while(*s++ = *t++ && n--> 0);? 有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19556519/

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