test.c:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
// return赋值
char **char_set_v0(int *n)
{
char **p = (char **)malloc(3 * sizeof(char *));
if (p == NULL) {
printf("out of mem\n");
return NULL;
}
int i =0;
for (i=0; i<3; i++) {
*(p+i) = (char *)malloc(1024);
if (*(p+i) == NULL) {
printf("out of mem\n");
return NULL;
}
snprintf(*(p+i), 1023, "hello %d", i+1);
}
*n = 3;
return p;
}
// 参数赋值
int char_set_v1(char ***m)
{
char **p = (char **)malloc(3 * sizeof(char *));
if (p == NULL) {
printf("out of mem\n");
return 0;
}
int i = 0;
for (i=0; i<3; i++) {
p[i] = (char *)malloc(1024);
if (p[i] == NULL) {
printf("out of mem\n");
return 0;
}
snprintf(p[i], 1023, "hello %d", i+1);
}
*m = p;
return i;
}
int main(int argc, char **argv)
{
int i = 0;
int ret = 0;
printf(" ---- 0 ------\n");
char **p = NULL;
p = char_set_v0(&ret);
if (p != NULL) {
for(i=0; i<ret; i++) {
printf("[%d] %s\n", i, *(p+i));
}
for(i=0; i<ret; i++) {
if (*(p+i) != NULL) {
free(*(p+i));
*(p+i) = NULL;
}
}
free(p);
p = NULL;
}
printf(" ---- 1 ------\n");
char **m = NULL;
ret = char_set_v1(&m);
if (m != NULL) {
for(i=0; i<ret; i++) {
printf("[%d] %s\n", i, m[i]);
}
for(i=0; i<ret; i++) {
if (m[i] != NULL) {
free(m[i]);
m[i] = NULL;
}
}
free(m);
m = NULL;
}
return 1;
}
编译&执行:
gcc -g -o test test.c
./test