我需要在动态分配的char**中将特定索引处的所有元素右移,以便在数组中插入字符串。
我很困惑,我如何能够横向穿过存储在特定索引中的字符串,以便将它们向右移动?
函数接收并int index、指向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->数组是字符串数组这一事实。尝试对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->大小-1)。然后从末尾迭代到感兴趣的位置。

10-08 17:48