bjrnove said:
This should fix the problem mentioned above.
int AddString(char*** pppszStrings, char* pszString)
{
char** ppszStrings = *pppszStrings;
size_t nSize = 0;
nSize = StringsSize(ppszStrings);
if(!(ppszStrings = (char**)realloc(ppszStrings, sizeof(char**) *
(nSize + 2)))){
/* If this fail I will return without making any changes to the
* string assay. If it fail the first time everything is NULL
* anyway, so that shouldn't be a problem. */
return errno;
}
if(!(ppszStrings[nSize] = (char*)malloc(strlen(pszString) + 1))){
int nErr = errno;
/* If this fails it's a bit of a problem. My solution is to
* realloc the array back to it's original size. */
if(!(ppszStrings = (char**)realloc(ppszStrings, sizeof(char**)
* (nSize + 1)))){
/* This shouldn't be possible since you're asking for less
memory than you
* already have. */
return 123; /* Should be defined as an FATAL ERROR constant
of some
* kind. If you get an error here the system is
unstable,
* and your program should quit. */
}
No, you cannot simply realloc and return an error code. Either one
of the two realloc statements may move the array of pointers to a
new location. Therefore, the value of the char ** argument in function
main may no longer point to the array. See, below the function
modified that should correct the problem.
*pppszStrings = ppszStrings;
return nErr;
}
strcpy(ppszStrings[nSize], pszString);
ppszStrings[nSize + 1] = NULL;
*pppszStrings = ppszStrings;
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
size_t ArrayCount(char **p);
int AddString(char ***p, const char *s);
void PrintArray(char **p);
void FreeArray(char ***p);
int main(void)
{
char **name = NULL;
AddString(&name,"George Washington");
AddString(&name, "John Adams");
AddString(&name, "Bill Clinton");
AddString(&name,"George W. Bush");
AddString(&name, "Abraham Lincoln");
puts("\tContents of the array of strings");
PrintArray(name);
FreeArray(&name);
return 0;
}
size_t ArrayCount(char **p)
{
size_t tmp;
if(!p) return 0;
for(tmp = 0;(*p); p++,tmp++) ;
return tmp;
}
int AddString(char ***p, const char *s)
{
char **tmp, *s1;
size_t ele_nr = ArrayCount(*p);
if(!p || !s) return 0;
if((tmp = realloc(*p,(ele_nr+2)*sizeof *tmp)) == NULL)
return 0;
tmp[ele_nr] = tmp[ele_nr+1] = NULL;
*p = tmp;
if((s1 = malloc(strlen(s)+1)) == NULL)
return 0;
strcpy(s1,s);
tmp[ele_nr] = s1;
return 1;
}
void PrintArray(char **p)
{
for( ; *p; p++)
printf("%s\n",*p);
return;
}
void FreeArray(char ***p)
{
char **tmp;
for(tmp = *p ; *tmp; tmp++) free(*tmp);
free(*p);
*p = NULL;
return;
}