gpt4 book ai didi

c - 如何仅使用指针在 C 中重新调用字符串数组

转载 作者:行者123 更新时间:2023-11-30 14:43:48 25 4
gpt4 key购买 nike

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

如何仅使用指针来重新调用数组?我不希望它是这样的:“玩家 2”、“玩家 3”、“玩家 1”

最佳答案

看起来您想要进行左移(旋转)。
这是一个非常简单的操作

  • 将指针指向头部
  • 对于每个元素,使该点指向下一个元素
  • 把头放在尾部上

代码:

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

这给出:

$ ./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"

关于c - 如何仅使用指针在 C 中重新调用字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53716081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com