Dynamically Allocating a 2D Array.
Code:
#define _GNU_SOURCE 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/wait.h>
typedef enum
{
FALSE = 0,
TRUE = 1
} Bool;
int main()
{
ssize_t readReturn = 0;
size_t bufLen = 0;
char **Inputs = NULL;
char *input = NULL;
int x = 0;
Bool stillGoing = TRUE;
int num_of_inputs = 0;
int cols = 0;
int old_cols = 0;
int i = 0;
while(stillGoing)
{
printf("enter text: ");
readReturn = getline(&input, &bufLen, stdin);
for(x = 0; x < strlen(input) + 1; ++x)
{
if(input[x] == '\n')
{
input[x] = '\0';
}
}
num_of_inputs++;
cols = strlen(input) +1;
printf("maybe here (inputs realloc)\n");
Inputs = realloc(Inputs, num_of_inputs * sizeof(char *));
if(cols > old_cols)
{
for(i = 0; i < num_of_inputs; i++)
{
Inputs[i] = malloc(cols * sizeof(char));
}
old_cols = cols;
}
printf("maybe this is where it's seg faulted (strcpy)\n");
strcpy(&Inputs[num_of_inputs - 1][0], input);
if(strncmp(input, "exit", 4) == 0)
{
stillGoing = FALSE;
}
free(input);
input = NULL;
}
free(Inputs);
return 0;
}
i keep geting a seg fault i have no idea why. the program is supposed to add the user's input into a new row in the array. The array will end up looking like this: http://www.rafb.net/paste/results/9YpiYn61.html