首页 > 解决方案 > 为什么我不能将结构数组移动 1 个元素?

问题描述

我正在尝试将结构数组移动 1 个元素,然后擦除第一个元素,但由于某种原因,打印输出中缺少一个元素。起初,它看起来像是在大多数元素被移动的地方工作,但是在第 14 个条目附近应该有一个 33 并且不存在?为什么是这样?

struct msr{
int a;
int b;
int c;};

struct msr msr_struc[20];

int main(){
  int add_val = 0;

      //Initialise structure elements with some data
  for(int i = 0; i < 20; i++)
    msr_struc[i].b = i+20;

            //Shift the structure by 1 element
    memmove(&msr_struc[add_val+1], &msr_struc[add_val], (20-add_val-1)*sizeof(double));
            //Reset the first entry
    memset(&msr_struc[0], 0, sizeof(msr_struc[0]));

            //Print results
    for(int i = 0; i < 20; i++)
        printf("strc: %d \n", msr_struc[i].b);

    printf("MISSING: %d \n", msr_struc[14].b);


return 0;
 }


strc: 0 
strc: 20 
strc: 21 
strc: 22 
strc: 23 
strc: 24 
strc: 25 
strc: 26 
strc: 27 
strc: 28 
strc: 29 
strc: 30 
strc: 31 
strc: 32 
strc: 34 
strc: 35 
strc: 36 
strc: 37 
strc: 38 
strc: 39 
MISSING: 34 

标签: carraysstruct2dshift

解决方案


推荐阅读