Search code examples
cstringmemorydynamicallocation

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


I need to shift all elements at a particular index to the right in a dynamically allocated char ** so that I can insert a string in the array.

I am confused about how I can transverse through the string stored at a particular index so that I can move them to the right?

The function receives and int index, a pointer to struct SmartArray, and a char *str string that is to be inserted at said index.

Am I on the right track? Is this there a more efficient way to do this?

This is what I've come up with so far:

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;
   }

  }

}

This is the struct I am working with:

    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;

Solution

  • Looks like homework. Try to ignore the fact that sa->array is a string array. Try doing this exact operation over an int array.

    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++;
    }
    

    Edit: You should notice that your last item must always be at (sa->size - 1). Then iterate from the end to the position of interest.