I realize that this method is not really
optimal.
Better would be a simple linked list.
However I am curious to see if there is
anyone who has a proven method for doing this.
I have either a logic error in this code,
or am missing something basic.
char **arrayCreate(char **name, int r, int s) {
int y;
char **new = malloc(r * sizeof(char *));
if (new) {
for (y=0 ; y <= r; y++) {
new[y] = malloc(s * sizeof(char));
}
} else {
return NULL;
}
name = new;
return name;
}
Return/resize the array:
char **arrayResize(char **name, int rows, int old) {
int y;
char **cpy = malloc(rows * sizeof(char *));
printf("\nResizing at new %d and filling from %d elements\n\n",rows,old);
for (y=0 ; y <= old ; y++) {
cpy[y] = malloc(strlen(name[y]) + 1 * sizeof(char *));
strcpy(cpy[y],name[y]);
free(name[y]);
}
/* alloc trivial mem for new elements*/
for (y=old ; y <= (rows - old) ; y++) {
cpy[y] = malloc(1 * sizeof(char));
}
free(name);
return cpy;
}
And snippet of main:
sarrpt = arrayCreate(sarrpt,irows,isize);
if (sarrpt != NULL && (mydir = opendir(argv[1])) != NULL) {
while ((en = readdir(mydir)) != NULL) {
if (y > irows) {
sarrpt = arrayResize(sarrpt,(y + 10),irows);
irows = y + 9;
}
sarrpt[y] = realloc(sarrpt[y],strlen(en->d_name) + strlen(argv[1]) + 1 * sizeof(char));
if (sarrpt[y] == NULL) {
printf("Error memallocation!\n"
return 1;
}
strcpy(sarrpt[y],argv[1]);
strcat(sarrpt[y],en->d_name);
printf("%s %p\n",sarrpt[y], sarrpt[y]);
y++;
}
Better methods or references anyone?
optimal.
Better would be a simple linked list.
However I am curious to see if there is
anyone who has a proven method for doing this.
I have either a logic error in this code,
or am missing something basic.
char **arrayCreate(char **name, int r, int s) {
int y;
char **new = malloc(r * sizeof(char *));
if (new) {
for (y=0 ; y <= r; y++) {
new[y] = malloc(s * sizeof(char));
}
} else {
return NULL;
}
name = new;
return name;
}
Return/resize the array:
char **arrayResize(char **name, int rows, int old) {
int y;
char **cpy = malloc(rows * sizeof(char *));
printf("\nResizing at new %d and filling from %d elements\n\n",rows,old);
for (y=0 ; y <= old ; y++) {
cpy[y] = malloc(strlen(name[y]) + 1 * sizeof(char *));
strcpy(cpy[y],name[y]);
free(name[y]);
}
/* alloc trivial mem for new elements*/
for (y=old ; y <= (rows - old) ; y++) {
cpy[y] = malloc(1 * sizeof(char));
}
free(name);
return cpy;
}
And snippet of main:
sarrpt = arrayCreate(sarrpt,irows,isize);
if (sarrpt != NULL && (mydir = opendir(argv[1])) != NULL) {
while ((en = readdir(mydir)) != NULL) {
if (y > irows) {
sarrpt = arrayResize(sarrpt,(y + 10),irows);
irows = y + 9;
}
sarrpt[y] = realloc(sarrpt[y],strlen(en->d_name) + strlen(argv[1]) + 1 * sizeof(char));
if (sarrpt[y] == NULL) {
printf("Error memallocation!\n"
return 1;
}
strcpy(sarrpt[y],argv[1]);
strcat(sarrpt[y],en->d_name);
printf("%s %p\n",sarrpt[y], sarrpt[y]);
y++;
}
Better methods or references anyone?