広告
↓発売日:2018年09月22日↓
![]() |
新品価格 |
今回は2つの要素の入れ替えをやります。
#include <stdio.h>
int main(){
int a = 100;
int b = 200;
int tmp = 0;
printf("a = %d,b = %d\n\n",a,b);
tmp = a;
a = b;
b = tmp;
printf("a = %d,b = %d\n\n",a,b);
return 0;
}
変数「a」と「b」を普通に入れ替えてみます。
int a = 100; int b = 200;
入れ替え用の変数を用意します。
int tmp = 0;
この入れ替え用の変数を間に挟んで入れ替えをします。
tmp = a; a = b; b = tmp;
これで入れ替え完了です!
#include <stdio.h>
void my_swap(int* ,int* );
int main(){
int a = 100;
int b = 200;
printf("a = %d,b = %d\n\n",a,b);
my_swap(&a,&b);
printf("a = %d,b = %d\n\n",a,b);
return 0;
}
void my_swap(int* a,int* b){
int w;
w = *a;
*a = *b;
*b = w;
}
入れ替え用の関数を作ります。
2つの変数のアドレスを渡して入れ替えていきます。
int a = 100; int b = 200; my_swap(&a,&b);
入れ替え用関数「my_swap()」になります。
void my_swap(int* a,int* b){
int w;
w = *a;
*a = *b;
*b = w;
}
「*a」→内容、「a」→アドレスを間違えないように内容を入れ替えて完了です!
広告
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
struct STUDENT{
char name[128];
int age;
};
struct STUDENT set_data(const char* , int);
void my_swap2(struct STUDENT* ,struct STUDENT* );
int main(){
struct STUDENT student[2];
int i;
student[0] = set_data("tanaka",15);
student[1] = set_data("suzuki",12);
for(i=0;i<2;i++){
printf("%d:%s %d\n",i,student[i].name,student[i].age);
}
my_swap2(&student[0],&student[1]);
printf("\n");
for(i=0;i<2;i++){
printf("%d:%s %d\n",i,student[i].name,student[i].age);
}
return 0;
}
struct STUDENT set_data(const char* name, int age){
struct STUDENT tmp;
strcpy(tmp.name,name);
tmp.age = age;
return tmp;
}
void my_swap2(struct STUDENT* a,struct STUDENT* b){
struct STUDENT tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
より実用的なプログラムにおいては構造体の入れ替えも必要になってくるかもしれません。
struct STUDENT{
char name[128];
int age;
};
struct STUDENT student[2];
こちらの2つの構造体を入れ替えます。
my_swap2(&student[0],&student[1]);
それぞれのアドレスを渡して入れ替えます。
void my_swap2(struct STUDENT* a,struct STUDENT* b){
struct STUDENT tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
引数が構造体になるだけで後は構造体でもメンバを指定せずに入れ替えれば丸ごと入れ替える事ができます。
広告
↓発売日:2016年02月29日↓
![]() |
12歳からはじめる ゼロからのC言語 ゲームプログラミング教室 新品価格 |
↓発売日:2018年06月22日↓
![]() |
新品価格 |
↓発売日:2018年03月09日↓
![]() |
新品価格 |
↓発売日:2017年06月14日↓
![]() |
新品価格 |
↓発売日:2018年05月21日↓
![]() |
新品価格 |
↓発売日:2017年12月07日↓
![]() |
新品価格 |
↓発売日:2017年02月08日↓
![]() |
新・明解C言語で学ぶアルゴリズムとデータ構造 (明解シリーズ) 新品価格 |
↓発売日:2017年09月26日↓
![]() |
新品価格 |