如何将元素移动到 c 中动态分配的 char ** 指针的右侧?我在正确的轨道上吗?

How to move elements to the right of a dynamically allocated char ** pointer in c? Am I on the right track?

我需要将动态分配的 char ** 中特定索引处的所有元素向右移动,以便我可以在数组中插入一个字符串。

我对如何横穿存储在特定索引处的字符串以便将它们向右移动感到困惑?

该函数接收 int 索引、指向 struct SmartArray 的指针以及要插入到所述索引处的 char *str 字符串。

我走在正确的轨道上吗?有更高效的方法吗?

这是我到目前为止的想法:

char *insertElement(SmartArray *smarty, int index, char *str)
{
  int i;
  char temp;

  // Any elements to the right of index are shifted one space to the right., not sure if this is correct way to find strlen
  for (i = index; i < strlen(smarty->array[index]); i++)
  {
    temp = smarty->array[index]
    if (i == index)
    {
      smarty->array[index] = str[i];
    }
   else
   {
     smarty->array[index] = temp;
   }

  }

}

这是我正在使用的结构:

    typedef struct SmartArray
{
    // We will store an array of strings (i.e., an array of char arrays)
    char **array;

    // Size of array (i.e., number of elements that have been added to the array)
    int size;

    // Length of the array (i.e., the array's current maximum capacity)
    int capacity;

} SmartArray;

看起来像作业。尽量忽略 sa->array 是一个字符串数组这一事实。尝试对 int 数组执行此精确操作。

void insert(SmartArray* sa, int indexWhereInsert, char* stringToInsert){
  // upper bound of indexWhereInsert?
  if( !(0 <= indexWhereInsert && indexWhereInsert < sa->size) ){
    printf("Do something about bounds...");
    return;
  }

  // Lets make sure there is always space
  if( sa->capacity < sa->size+1 ) 
    increaseCapacity(sa); // Usually double it

  // We move all strings at the right of indexWhereInsert one position to the right
  for(int index = sa->size - 1 ; index >= indexWhereInsert; index--){
    sa->array[index+1] = sa->array[index];
  }

  // Finally we insert the new string
  sa->array[indexWhereInsert] = stringToInsert;
  sa->size++;
}

编辑: 您应该注意到您的最后一项必须始终为 (sa->size - 1)。然后从末尾迭代到感兴趣的位置。