ページ 11

文字列の格納について

Posted: 2015年12月15日(火) 15:40
by Toshita
すごく初歩的な質問ですが、下記のチェイン法を用いた
プログラムなのですが、
1,名前と年齢を入れていく
2,"-"が入力された時点で終了
3,年齢をkeyにし、該当者の名前を検索
という流れなのですが、
%sでちゃんと文字列にしているつもりなのですが、
どうしうても一文字しか格納してくれません。
どうしてでしょうか。
※9文字以上入力するとコアダンプします。

コード:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define BUCKET_SIZE 9		

struct node{
	int age;		/*氏名*/
	char name;		/*年齢*/
	struct node *next;
};

struct node *table[BUCKET_SIZE];


void init(){			/*ハッシュ表初期化*/
	int i;
	for(i=0; i<BUCKET_SIZE; i++) table[i] = NULL;
}

int hash(int age){		/*ハッシュ関数*/
	return age % BUCKET_SIZE;
}

int keyequal(int age1,int age2){
	if(age1 == age2) return 1;
	else return 0;
}

char *find(int age){
	struct node *cur;
	int h = hash(age);
	
	for(cur = table[h]; cur != NULL; cur = cur->next){
		if(keyequal(age,cur->age) == 1) return &cur->name;
	}
	return NULL;
}

int insert(){
	char name;
	int age,h;
	
	do{
		printf("氏名:"); scanf("%s",&name);
		if(name != '-'){
			printf("年齢:"); scanf("%d",&age);
		}
		else break;
		
		struct node *new =(struct node*)malloc(sizeof(struct node));
		if(new == NULL) {printf("ERROR-1"); return 0;}
		
		new->age = age;
		new->name = name;
		h = hash(age);
		new->next = table[h];
		table[h] = new;
	
	}while(name != '-');
}

int main(void){
	int age;
	struct node *human;
	init();
	insert();
	
	printf("検索します\n年齢:"); scanf("%d",&age);
	printf("対象者は %s 様です",find(age));
	
	return 0;
}

Re: 文字列の格納について

Posted: 2015年12月15日(火) 17:19
by みけCAT
Toshita さんが書きました:%sでちゃんと文字列にしているつもりなのですが、
どうしうても一文字しか格納してくれません。
どうしてでしょうか。
一文字しか格納できないchar型の変数を使っているからです。
ちなみに、終端のヌル文字も一文字なので、このプログラムには名前として0文字しか入力できません。
文字列を扱うには、char型の配列を用いるといいでしょう。

Re: 文字列の格納について

Posted: 2015年12月22日(火) 12:55
by Toshita
できました;
charって1文字だけだったんですね;