LoginSignup
0
1

More than 5 years have passed since last update.

C言語で動的確保された文字列配列の要素をswapする関数

Last updated at Posted at 2018-12-24

内容

arrで渡される文字列配列のa番目とb番目を入れ替えます。

注意点

  • reallocが失敗することは考慮してません。
  • reallocでの注意点はすべて当てはまります。

コード

str_swap.c
#include <stdlib.h>
#include <string.h> 

void str_swap(char** arr, int a,int b ){
    char* tmp = realloc(tmp,sizeof(char)*(strlen(arr[b])+1));
    strcpy(tmp,arr[b]);
    arr[b] = realloc(arr[b],sizeof(char)*(strlen(arr[a])+1));
    strcpy(arr[b],arr[a]);
    arr[a]= realloc(arr[a],sizeof(char)*(strlen(tmp)+1));
    strcpy(arr[a],tmp);
    free(tmp);
}

経緯

文字列の長さが違う要素を持った文字列配列の任意の要素をswapする必要があった。
各要素は自身の長さちょうどのメモリしか確保されていないので、それ以上の長さの文字列を代入できない。
てことでreallocしちゃいました。

その他

初投稿!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1