[ create a new paste ] login | about

Link: http://codepad.org/SxUWkr6F    [ raw code | output | fork ]

C, pasted on Dec 14:
#include <stdio.h>
#include <stdlib.h>	//for exit() calloc()
#include <string.h>	//strlen,strcpy

void Matrix_free(char **p,int num);

int main(void)
{
	char	**pt,
		temp[128];
	int	num,
		i,	//カウンタ
		len;	//文字列の長さ

	printf("文字列数:");
	scanf("%d",&num);
	pt=(char**)calloc(num,sizeof(char*));
	if(pt==NULL){	//エラー処理
		printf("記憶領域の確保に失敗しました\n");
		exit(1);
	}

	for(i=0;i<num;i++){
		pt[i]=NULL;
	}

	for(i=0;i<num;i++){
		printf("文字列を入力:");
		scanf("%s",temp);

		len=strlen(temp);
		pt[i]=(char*)calloc(len+1,sizeof(char));
		if(pt[i]==NULL){
			printf("記憶領域の確保に失敗しました\n");
			Matrix_free(pt,num);
			exit(0);
		}
		strcpy(pt[i],temp);
	}

	for(i=0;i<num;i++){
		printf("pt[%d]=%s\n",i,pt[i]);
	}

	Matrix_free(pt,num);	//確保していた領域の開放

	return 0;
}

//確保した全領域の開放
void Matrix_free(char **p,int num)
{
	int i;

	for(i=0;i<num;i++){
		free(p[i]);	//pt[i]が指す領域を開放
	}
}


Output:
1
文字列数:記憶領域の確保に失敗しました


Create a new paste based on this one


Comments: