Reputation: 365
I'm trying to create a dynamic char** of words as they are read in from getline()
while ((lineLength = getline(&line, &n, stdin)) != -1) {
if(lineLength > 0)
{
if(line[lineLength - 1] == '\n')
{
line[lineLength - 1] = '\0';
}
}
}
but I'm having issues using malloc() to create the element and dynamically allocate the memory for it. I'm currently trying to
char** words = (char**)malloc(x*sizeof(char));
but am getting errors. What is the best way to accomplish this?
Upvotes: 0
Views: 47
Reputation: 731
sizeof(char)
is different than sizeof(char*)
. sizeof(char)
is generally 1, while the size of a pointer is implementation-defined, but always larger than that. You really aren't allocating enough room for your pointer. Because you have a pointer of pointers, I think the code you really want is
char** words = (char**)malloc(x*sizeof(char*));
Upvotes: 2