C复杂循环问题

时间:2014-05-04 21:45:27

标签: c

我正在尝试修改一个能够处理语音的小代码。现在我遇到了一个小障碍。我有一个计数器int i,我有一个由32个整数组成的数组file。我想要做的是当我的计数器i达到4时,它应该将file数组中的所有值复制到newarray。这将继续告诉file数组的结束。在下面的代码中,我可以选择前3次然后它继续并且当它是4时不会停止。我尝试了各种方式;但是,我无法解决它。

int filesize = 34;
int newsize=4;

int file[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34}; 
int arraynew[newsize];

int begin =0;
int end = newsize;

int i=0;
int j=0;

while(begin < filesize){
  arraynew[begin] = file[begin];
  i++;
  printf(" I is:%d\n",i); 
  if(i== 4){
    i=0; 
    printf("Rest  I is:%d\n",i);         
    int start=0;
    int mid = (start + end)/2, m=0;
    for(;mid < end; mid++){
      arraynew[start+m] = arraynew[mid];
      m++;                      
    }  //shift array 2 places to the left and add 
       // another two value at the end then
       // pass to function.
  }
  begin++;                                
}

上述代码的结果:

 I is:1
 I is:2
 I is:3
 I is:4
Rest  I is:0
 I is:1
 I is:2
 I is:3
 I is:4
Rest  I is:0
 I is:1
 I is:2
 I is:3
 I is:4
Rest  I is:0
 I is:14
 I is:15
 I is:16
 I is:17
 I is:18
 I is:19
 I is:20
 I is:21
 I is:22
 I is:23
 I is:24
 I is:25
 I is:26
 I is:27
 I is:28
 I is:29
 I is:30
 I is:31
 I is:32
 I is:33
 I is:34

1 个答案:

答案 0 :(得分:0)

我建议使用以下代码。

#include <stdio.h>
#include <string.h>

void print(int *array, int size){
    while(size--)
        printf("%d ", *array++);
    printf("\n");
}   

int main(){
    int file[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34}; 
    int filesize = sizeof(file)/sizeof(*file);
    int newsize=4;
    int arraynew[newsize];
    int i, m = newsize / 2;

    for(i=0; i + newsize -1 < filesize; i+= m){
        memcpy(arraynew, &file[i], sizeof(arraynew));
        print(arraynew, newsize);//print(&file[i], newsize);
    }
    return 0;
}