为什么我的 for 循环中的 strncpy 无效?

Why is strncpy in my for loop uneffective?

我正在尝试将一个字符串拆分为多个小字符串(nb 大小)。 但它没有像我想要的那样工作:

 #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <sys/types.h>
int main(int argc, char *argv[]) {
  char *source = argv[1];
  int taille=0;
  int i=0;
  int k;
  int nb = 5;
  char dest[strlen(source)/nb][nb];
  while(i<strlen(source))
  {
    char *src = &source[i];
    strncpy(dest[taille],src,nb);
    i=i+nb;
    taille++;
  }

    for(k = 0 ; k <8;k++)
  {
    printf("\t%s\n",dest[k]);
  }
}

这是痕迹:

jerome@debian:~/codeFTP/code/serveur$ ./a.out " bonjour cocoman, tu me donne20 balles?"
     bonjour cocoman, tu me donne20 balles?
    our cocoman, tu me donne20 balles?
    ocoman, tu me donne20 balles?
    n, tu me donne20 balles?
     me donne20 balles?
    onne20 balles?
    0 balles?
    les?

但最奇怪的是,如果我去掉 while(或 thefor,我都试过了),它会起作用(通过取消 while 我的意思是用适当的值而不是使用循环编写 strncpy 8 次) . 感谢您的关注。

strncpy 不会空终止字符串。你需要自己做。当您 printf 第一个时,printf 永远不会找到 null 并开始打印内存中发生的任何内容。因为它们在数组中,所以它看到的下一个字节是下一个字符串的第一个字节。这一直持续到它到达最后一个字符串,该字符串以 null 终止,因为 strncpy 实际上看到了源字符串的结尾。

您需要更改您的声明以在每个字符串中为空字符保留一个字节:

char dest[strlen(source)/nb][nb + 1];

然后在复制后手动以 null 终止每个子字符串:

dest[taile][nb] = 0;

我不确定展开循环的原因 - 当您重写它时,您的其他逻辑可能略有变化。

编辑添加:此外,正如 Gopi 在他们的回答中所说,您用于查找字符串数量的数学四舍五入。如果字符串长度不是 nb 的完美倍数,那么您的数组太小并且您正在调用未定义的行为。最简单的解决方案是也向该维度添加一个。您的循环是安全的,因为它基于 strlen,而不是您计算的子字符串数。

char dest[strlen(source)/nb + 1][nb + 1];

存在潜在问题

strlen(source)/nb 作为索引,与 strlen(source) 相比,这将具有最少的行,并且您正在执行以下

  while(i<strlen(source))
  {
    char *src = &source[i];
    strncpy(dest[taille],src,nb);
    i=i+nb;
    taille++;
  }

现在dest[taille]必然是数组越界访问,还要确保

strncpy() 不会 [=15=] 终止字符串。

基本情况:传递一些长度小于 5 的字符串,你就有了 UB。您的代码中存在多个此类潜在错误。