补充:给二级指针分配空间

前面有生篇文章“给二级指针分配空间”,分配的空间有点问题,不连续,正确的分配方法如下面的例子。以下例子实现的功能是:把文件当中的每一行读到一个数组中的一个char*里面。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef	_WORDSLEN_
#define WORDSLEN 32
#endif

#define PRINTERR(errMsg)	printf("error:%s",errMsg)
#define FREEIF(ptr)		{if (ptr) free(ptr);}
#define CLOSEIF(fptr)		{if (fptr)	fclose(fptr);}

int load2Var(char *filename, char arr[][WORDSLEN])
{
	FILE *fin = NULL;
	char *text = NULL;	//the content of the file text
	char *ptr;
	int textLen = 0;
	int i = 0;
	char *delim  = "\n ";

	if (!(fin = fopen(filename,"r")))
	{
		PRINTERR("filename\n");
		return -3;
	}

	fseek (fin,0L,SEEK_END);
	textLen = ftell (fin);
	fseek (fin,0L,SEEK_SET);

	do
	{
		if (!(text = (char *)calloc(textLen+1,sizeof(char))))
		{
			PRINTERR("calloc\n");
			break;
		}

		fread(text,textLen,1,fin);

		ptr = (char *)strtok(text,delim);		
		while (ptr)
		{			
			strcpy(arr[i], ptr);		
			ptr=(char *)strtok(NULL,delim);
			i++;
		}

	}while(0);

	FREEIF(text);
	CLOSEIF(fin);
	return i;
}

int main(int argc, char **argv)
{
	int len = 0, i = 0;	
	char **myarr = NULL;

	
	if (!(myarr = (char **)malloc(WORDSLEN*sizeof(char *))))
	{
		printf("malloc myarr err");
		return -1;
	}
	*myarr = (char *)malloc(sizeof(char) * WORDSLEN * WORDSLEN);
	if (myarr[0] == NULL)
	{
		return -2;
	}
	for (i = 0; i < WORDSLEN; i++)
	{
		myarr[i] = (char *)myarr[0] + WORDSLEN * i;
	}

	memset(myarr[0],0,WORDSLEN*WORDSLEN);

	len = load2Var("input.txt", *myarr);

	printf("Len=%d\n",len);

	for (i = 0; i < WORDSLEN; i++)
	{
		if (strlen(myarr[i]) > 0)
			printf("%s \n", myarr[i]);
	}

	FREEIF(*myarr);

	FREEIF(myarr);

	return 0;
}

你可能感兴趣的:(指针)