指针数组堆上分配内存(动态分配内存)

来源:互联网 发布:小米机顶盒下载软件 编辑:程序博客网 时间:2024/05/22 06:12
#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>#include <stdlib.h>#include <string.h>char **allocateSpace(int len){if (len <= 0){return NULL;}char **temp = (char **)malloc(sizeof(char *)*len);if (temp == NULL){return NULL;}memset(temp, 0, sizeof(char *)*len);for (int i = 0; i < len; i++){temp[i] = (char *)malloc(100);if (temp[i] == NULL){goto End;}memset(temp[i], 0, 100);sprintf(temp[i], "%2d_hello world!", i + 1);}return temp;End:for (int i=0;i<len;i++){if (temp[i] != NULL){free(temp[i]);temp[i] = NULL;}}free(temp);temp = NULL;return NULL;}void freeAll(char **str, int len){if (str == NULL){return;}for (int i = 0; i<len; i++){if (str[i] != NULL){free(str[i]);str[i] = NULL;}}free(str);str = NULL;}void test(){char **p = NULL;p = allocateSpace(10);for (int i = 0; i < 10; i++){printf("%s\n", p[i]);}freeAll(p, 10);}void main(){test();system("pause");}

0 0