我需要在动态分配的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;
答案 0 :(得分:2)
看起来像家庭作业。尽量忽略sa-&gt;数组是一个字符串数组的事实。尝试对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)。然后从结尾迭代到感兴趣的位置。