LoginSignup
1
0

More than 5 years have passed since last update.

C言語の構造体を(少し)工夫して使ってみる

Posted at

char型の配列の一部分を取り出す方法。

配列animalsから"crocodile"という文字列を取り出したい場合

main.c
 #include <stdio.h>
 #include <string.h>

 typedef struct
 {
     char inu[3];
     char neko[3];
     char neko2[4];
     char wani[9];
     char tori[4];
 }ZOO;

 int main()
 {
     char animals[] = "dogcatlioncrocodilebird";
     char wani[10];  //コピー先配列
     memset(wani, '\0', sizeof(wani)); //初期化
     ZOO* ZooP = (ZOO*)animals;        //構造体の型に当てはめる
     memcpy(wani, ZooP->wani, sizeof(ZooP->wani));  //構造体の一部をコピー
     printf("%s\n", wani);

     return 0;
 }   

output:crocodile

char型の配列を構造体の型に当てはめるようなイメージ
構造体の型に当てはめてあげれば他の文字列も取り出すことができるため便利

1
0
1

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
1
0