0

I have to copy one array to another. Both of them are in int* form. I have to copy it till the index reads -1, but it keeps on copying. I tried using the debugger. After reaching -1 it carries on copying data in the rest of the vertices.

void copy(int *a, int *b)
{
    int i=0;

    while(a[i]!=-1)
    {
        if(a[i]==-1)
            break;
        //for( i=0; a[i]!=-1; i++)
            a[i]=b[i];
        i++;
    }

    a[i]=b[i];
}


copy(temp->patharray,num);

patharray and num are both int*

4

3 回答 3

2

看起来您想要复制到-1源数组中,但是您的所有检查都针对目标数组中的先前值

while(b[i]!=-1)
{ 
   a[i] = b[i];
   i++;
}

旁注:具有良好的变量名称使代码更易于阅读和理解 - 尝试

void copy(int *destination, int *source, int maxLength) 
{
  int currentIndex = 0;

  while(currentIndex < maxLength && source[currentIndex] != -1)
  {
     destination[currentIndex] = source[currentIndex];
     currentIndex++;
  }
}
于 2013-05-04T02:16:30.210 回答
0

a[i] 增加i. 这意味着您尚未分配a[i]. 可能你应该检查b[i] != -1.

于 2013-05-04T02:17:45.403 回答
0

假设数组 b 的大小等于数组 a,

void copy(int *a, int *b)
{
    int i=0;

    while(b[i]!=-1)  
    {
        a[i]=b[i];
        i++;
    }
}
于 2013-05-04T02:23:04.220 回答