c - Using Double Pointers after memory allocated within function -
i playing double pointers in c , wondering if create function initializes table, crashes on going main when try make use of memory allocated initstringtable. believe simple fix make strtable global , believe ok, prefer not more of learning exercise me in passing table around modification i.e. should able modify strtable main or function modifytable after initstringtable. can give.
int main() { char** strtable; // allocates memory string table. initstringtable(strtable); // below lines should able copy strings newly allocated table. // below lines cause crash however. strcpy(strtable[0], "abcdef"); strcpy(strtable[1], "xy"); } // allocates memory string table. function should create table // of size 10 strings each string 50 chars long. code compiles fine. void initstringtable(char** table) { int = 0; table = (char**)malloc(sizeof(char)*10); for(i = 0; < 10; i++) { table[i] = (char*)malloc(sizeof(char)*50); } for(i = 0; < 10; i++) { memset(table[i], 0, 50); } strcpy(table[0], "string1"); }
c pass value.
the value assigned table
lost on returning initstringtable()
.
also when allocating pointers char
ask room pointers char
.
so this:
... = (char**)malloc(sizeof(char)*10);
shall @ least (assuming c):
... = malloc(sizeof(char*)*10);
a possible approach be:
#include <stdlib.h> #include <string.h> #include <errno.h> int initstringtable(char *** ppptable, const size_t n, const size_t l) { int result = 0; if (null == ppptable) { result = -1; errno = einval; } else { (*ppptable) = malloc(n * sizeof(**ppptable)); if (null == (*ppptable)) { result = -1; } else { size_t = 0; for(; < n; ++i) { (*ppptable)[i] = calloc(l, sizeof(*(*ppptable)[i])); if (null == (*ppptable)[i]) { result = -1; /* failing in middle requires clean-up. */ (; > 0; --i) { free((*ppptable)[i-1]); } free(*ppptable); (*ppptable) = null; break; } } } } return result; }
call this:
#include <stdlib.h> #include <stdio.h> int initstringtable(char *** ppptable, const size_t n, const size_t l); int main(void) { int result = exit_success; char ** strtable = null; if ( -1 == initstringtable(&strtable, 10, 42)) //* allocate array 10 "strings" à 42 chars. */ { perror("initstringtable() failed"); result = exit_failure; } else { strcpy(strtable[0], "abcdef"); strcpy(strtable[1], "xy"); } return result; }
and no, won't ridiculous "you don't wanna 3-star-programmer!" discussion.
Comments
Post a Comment