c++ - '--p' 在 for(p=&(*L).elem[(*L).length-1];p>=q;--p) 中如何工作?

标签 c++ c loops for-loop decrement

我正在尝试调试以下代码:

Status ListInsert_Sq(SqLIst *L, int i, LElemType_Sq e)
{
    LElemType_Sq *newbase;
    LElemType_Sq *p, *q;

    if(i<1 || i>(*L).length+1)
        return ERROR;                   
    if((*L).length >= (*L).listsize)
    {
        newbase = (LElemType_Sq*)realloc(LElemType_Sq *)realloc((*L).elem, ((*L).listsiz+LISTINCREMENT)*sizeof(LElemType_Sq));
        if(!newbase)
            exit(OVERFLOW);

        (*L).elem = newbase;
        (*L).listsize += LISTINCREMENT; 
     } 

     q = &(*L).elem[i-1];
     for(p=&(*L).elem[(*L).length-1];p>=q;--p)
        *(p+1) = *p;

    *q = e;
    (*L).length++;

    return OK;
} 

这里使用--p正确吗? 具体来说,我想知道列表的最后一个元素是否会被前一个元素移动或覆盖?

谢谢!

最佳答案

重写后,代码的猜测意图如下:

<小时/>
#include <stdlib.h>
#include <string.h>
#include "listmeuk.h"

Status ListInsert_Sq(SqLIst *lp, int index, LElemType_Sq elem)
{
    if(index<1 || index>lp->length+1) return ERROR; // this assumes 1-based indexing
    index--; // transform to zero-based indexing

    if(lp->length >= lp->listsize)
    {
        LElemType_Sq *newbase;
        newbase = realloc(lp->elem, (lp->listsiz+LISTINCREMENT) *sizeof *newbase);
        if(!newbase) exit(OVERFLOW);

        lp->elem = newbase;
        lp->listsize += LISTINCREMENT; 
     } 

    if(index < lp->length) memmove(&(lp->elem[index+1]), &(lp->elem[index]), (lp->length-index) * sizeof lp->elem[0] );

    lp->elem[index] = elem;
    lp->length++;

    return OK; 

} 

关于c++ - '--p' 在 for(p=&(*L).elem[(*L).length-1];p>=q;--p) 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58048089/

相关文章:

R - 向量化哪个操作

c++ - 重新启动后禁用USB键盘

c++ - 在 C++ 中获取对象的数组索引

android - android studio预建库中的问题

c - 大约运行时间

r - 带小数的 for 循环并将结果存储在向量中

c++ - 包括头文件(包括它们自己)

C 编程不断崩溃

c - 获取变量的十六进制地址作为 uintptr_t

javascript - React 从循环结果中存储 prop 值