当我尝试运行此代码时,我在标题中收到错误:
//Copies the information from one array to another until a set length using pointers
void strncpy2(char* t, const char* s, const unsigned int n)
{
unsigned int i;
for (i = 0; i < n /* This i < n causes the error */ && *t++ = *s++; i++);
*(t + i) = '\0';
}
当我取出i < n
时,它可以正常工作,当我将i < n
移到*t++ = *s++
的右侧时,我没有收到任何编译错误,但代码并没有这样做。按预期工作。
这里发生了什么?我感谢任何帮助。谢谢!
答案 0 :(得分:2)
循环中的赋值周围需要括号,因为&&
运算符的优先级高于赋值。试试这个:
for (i = 0; i < n && (*t++ = *s++); i++);
答案 1 :(得分:0)
您的通话语义不明确,尤其是与strncpy()明显不同。
您似乎操纵原始字符串,但是您没有检查字符串的结尾,这是不安全的。
此外,循环后的赋值使用&#34; t&#34;作为基指针,因为你修改它是错误的。
我不知道&#34; n&#34;暗示t的大小,如果t必须至少为大小n,则必须停止在n-2处迭代或者你的最终赋值超出范围。
最后,我远离在for循环标题中有副作用的代码。
void strncpy2(char* t, const char* s, const unsigned int n)
{
unsigned int i;
for (i = 0; i < n-1; i++) {
t[i] = s[i];
if(s[i] == '\0') return;
}
t[i] = '\0';
}
如果你想使用指针追逐(c):
void strncpy2(char* t, const char* s, const unsigned int n)
{
unsigned int i;
for (i = 0; i < n-1; i++) {
*t = *s;
if(*s == '\0') return;
t++; s++;
}
*t = '\0';
}
现在我不知道这样做有什么意义,已经在标准库中使用了strncpy()和memcpy()。当然,C ++代码应该避免使用原始字符串;)