0
char * players[3]={"Player 1","Player 2","Player 3";
char *p = *players;
char *temp;
for(int t = 0; t < 2; t++)
     {
         temp = *(p+t);
         *(p+t) = *(p+t+1);
         *(p+t+1) = temp;
     }

How can I resort the array using pointers only ? I wan't it to be like this : "Player 2","Player 3", "Player 1"

1 Answers1

1

It looks like you want to do a left-shift (rotation).
This is a pretty simple operation

  • Keep a pointer to the head
  • For every element, make that spot point to the next element
  • put the head on the tail

The Code:

#include <stdio.h>

void rotateLeft( char **arr, int elements )
{
    // keep a pointer to the head
    char *head = arr[0];

    // shift every element left
    for (int i=0; i<(elements-1); i++)
    {
        arr[i] = arr[i+1];
    }

    // put the head on the tail
    arr[elements-1] = head;
}

// EDIT - rotate without [] notation.
void rotateLeftNoArrayNotation( char **arr, int elements )
{
    // keep a pointer to the head
    char *head = *arr; //arr[0];

    // shift every element left
    for (int i=0; i<(elements-1); i++)
    {
        *(arr+i) = *(arr+i+1); //arr[i] = arr[i+1];
    }

    // put the head on the tail
    *(arr+elements-1) = head; //arr[elements-1] = head;
}

int main( void )
{
    char *players[3] = { "Player 1", "Player 2", "Player 3" };

    for (int i=0; i<3; i++)
        printf( "players[%u] = \"%s\"\n", i, players[i] );

    rotateLeftNoArrayNotation( players, 3 );

    for (int i=0; i<3; i++)
        printf( "players[%u] = \"%s\"\n", i, players[i] );

    return 0;
}

Which gives:

$ ./rotLeft
players[0] = "Player 1"
players[1] = "Player 2"
players[2] = "Player 3"
players[0] = "Player 2"
players[1] = "Player 3"
players[2] = "Player 1"
Kingsley
  • 14,398
  • 5
  • 31
  • 53
  • Yes, exactly, But I wanna do it using pointers, without using any of [ ]. – Yamen Massalha Dec 11 '18 at 01:51
  • 1
    @YamenMassalha subscripting via `[ ]` is just as applicable against a pointer as it is against an array (which converts to pointer-to-first-element when use in an expression context, i.e. almost everywhere except decl). The expression `*(p+i)` is synonymous with `p[i]` whether `p` is an array or a pointer. So the statement "I wanna do it using pointers" is irrelevant. what you're really saying is you want to do it without using array subscript notation (apparently), applied anywhere (pointer or otherwise). Is that correct ? – WhozCraig Dec 11 '18 at 02:33
  • @YamenMassalha - I updated the answer, see `rotateLeftNoArrayNotation()` - basically it's the same function, slightly different syntax. Syntax that would not pass a code review ;) – Kingsley Dec 11 '18 at 03:28