2d字符串数组和Strcpy错误?

时间:2013-03-05 22:07:16

标签: c arrays strcpy

我遇到了为二维数组字符串赋值的问题。这是代码:

  Char array[]= "Nary had a little lamb";
  int chunkSize = 4;
  char inventory[totalRuns][chunkSize];

  subString(result, array,0,0+chunkSize);
  printf("CHUNK 1 = %s\n",result);          //Prints "Nary"
  strncpy(inventory[0],result,chunkSize);
  memset(result, '\0', strlen(result));

  subString(result, array,pos,pos+chunkSize);
  printf("CHUNK 2 = %s\n",result);          // Prints " had"
  strncpy(inventory[1],result,chunkSize);

函数substring:

char *subString(char* putHere, char* request,int start,int end){
    char* loc = request+start;
    char* end_loc = request+end;

    memcpy(putHere, loc, end_loc-loc);

    return putHere; 

}

当我运行此代码时,输​​出是

CHUNK 1 = Nary

CHUNK 2 =已经

这是正确的,但是当我打印库存时,我得到了

inventory[0]=Nary had       //Should be just "Nary"
inventory[1]= had           //correct

我在这里做错了什么想法?

1 个答案:

答案 0 :(得分:2)

如果在给定范围内没有0字节,则subString不会终止目标缓冲区,strncpy也不会终止0。因此,您的inventory包含未终止的char序列,并打印打印,直到printf在某处找到0字节或由于访问冲突而崩溃。

inventory的内存布局在inventory[1]的最后inventory[0]之后直接char,因此printf("%s", inventory[0]);打印两个块,因为第一个不是0结尾。在您的情况下,似乎紧接着有一个0字节,但由于inventory未初始化,这是巧合。