char*** 就像一个字符串表。
R\C ||---1-----|----2----|
|---1---||string11 |string12 |
|---2---||string21 |string22 |
|---3---||string31 |string32 |
| .... || ..... ...... |
|-(N-1)-||str N-1.1|str N-1.2|
|---N---||stringN1 |stringN2 |
这是一个带有 cmets 的演示源代码,以便了解如何实现类似的功能:
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
void rellocateFunction(size_t lenKey, size_t lenValue);
void firstAllocateFunction(size_t lenKey, size_t lenValue);
int i=0;
char*** tas;
int main(){
int j=0;
size_t length1, length2;
char* stringN1=(char *)malloc(10*sizeof(char));
char* stringN2=(char *)malloc(10*sizeof(char));
while(1){
printf("dragons\n");
printf("MAIN: Enter string[%d][0]:",j); scanf("%s", stringN1);
printf("MAIN: Enter string[%d][1]:",j); scanf("%s", stringN2);
length1 = strlen(stringN1); // You need the length of the string to pass it as an argumnet to allocation functions
length2 = strlen(stringN2); // Same as above comment
if(j==0) firstAllocateFunction(length1,length2); // We cant start with the use of realloc. So here you are initiliazing the allocation with calloc only.
else rellocateFunction(length1,length2); // When we already have entries in the table, we are going to use this function to allocate more memory for the new entries.
strcpy(tas[j][0],stringN1); // Population of char*** at row j and col 0
strcpy(tas[j][1],stringN2); // Population of char*** at row j and col 1
j++;
for (int c=0; c<j; c++) // Print the results
{
printf("tas[%d][0]:<%s>\n",c, tas[c][0]);
printf("tas[%d][1]:<%s>\n",c, tas[c][1]);
}
} // Notice the forever ongoing loop... That's to test if the code works. Cancel the execution with ctrl+c
return 0;
}
void firstAllocateFunction(size_t len1, size_t len2){
tas = (char ***)calloc(1,sizeof(char **)); //One char*** pointer
tas[i] = (char **)calloc(2,sizeof(char *)); //pointin to 2 char**
tas[i][0] = (char *)calloc(len1+1,sizeof(char)); //containing len1+1
tas[i][1] = (char *)calloc(len2+1,sizeof(char)); //and len2+1 elements of sizeof(char) bytes.
++i;
}
void rellocateFunction(size_t len1, size_t len2){
tas = (char ***)realloc(tas,sizeof(char **)*(i+1)); //One more char***
tas[i] = (char **)calloc(2,sizeof(char *)); ////////////////////
tas[i][0] = (char *)calloc(len1+1,sizeof(char)); // Same as above //
tas[i][1] = (char *)calloc(len2+1,sizeof(char)); ///////////////////
++i;
}
我使用了 calloc,因为我想避免使用 memset 来初始化字符串。其余的用 cmets 解释。
请注意,您必须在第一次使用不同的 function() 时为 char*** 分配内存,而不是在其余时间基本上重新分配 char*** 的内存。
警告。上面的代码没有实现 free() 函数(强烈推荐这样做。所以要小心不要让死数据填满你的内存。