Quote:
|
Can I do things like this with pointers to pointers?
|
The way you're using it there, No you cant.
The suggested function isn't valid.. And I think you know that too..
First off, you're using strcpy() which is provided in string.h, but you don't include it.
Second, you're accessing placeholder at index 0 of youre string_table struct pointer, this is an invalid assignment, since you crap on your orriginal deffinition of string_table
This is what I would do in that case:
Code:
/* somefile.h. */
#ifndef SOMEFILE__
#define SOMEFILE__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char **string_table;
int num_strings;
} string_table;
int add_str_to_table(string_table*, char*);
#endif
Code:
/* somefile.c */
#include "somefile.h"
int add_str_to_table(string_table* tbl, char* str)
{
tbl->string_table = (char**)realloc(tbl->string_table,
(tbl->num_strings +1)*sizeof(char*));
if(!tbl->string_table){
printf("Not enough heap space to reallocate string_table\n");
return -1;
}
tbl->string_table[tbl->num_strings] = (char*)malloc(strlen(str));
if(!tbl->string_table[tbl->num_strings]){
printf("Not enough heap space to allocate added string\n");
return -2;
}
if(!strcpy(tbl->string_table[tbl->num_strings], str)){
printf("Unable to copy str to placeholder\n");
return -3;
}
tbl->num_strings++;
return 0;
}
int main()
{
string_table * my_tbl;
int i;
char str1[] = "This is a string";
char str2[] = "This is a second string";
my_tbl = (string_table*)malloc(sizeof(string_table));
my_tbl->num_strings = 0;
if(0 != add_str_to_table(my_tbl, str1)){
printf("Unable to add str1\n");
return -1;
}
if(0 != add_str_to_table(my_tbl, str2)){
printf("Unable to add str2\n");
return -1;
}
for(i=0; i < my_tbl->num_strings; ++i)
printf("my_tbl->string_table[%d] = %s\n", i, my_tbl->string_table[i]);
return 0;
}