Reputation: 1595
I have char * lines[1000] string that can hold 1000 characters. How to create 100 arrays of that string. I get error with this code down.
char * lines[1000];
lines = (lines*)malloc(100 * sizeof(lines));
main.c:19:20: error: expected expression before ')' token
Upvotes: 3
Views: 4441
Reputation: 1575
It looks like you want an array strings, each string holding at most 1000 characters. There are some issues with your code.
You've declared an array of char *
s but what you really want is a pointer to an array of char
s. For that, your declaration should be
char (*lines)[1000];
On the other hand, you shouldn't forget about the NULL
bytes at the end of strings, and should probably instead declare
char (*lines)[1001];
To set the pointer, you'll want to use
lines = (char (*)[1001]) malloc(100 * sizeof(char[1001]));
or
lines = (char (*)[1001]) malloc(100 * sizeof(*lines));
the latter working because, with lines
a pointer to an array of char
s, *lines
is a char[1001]
. Remember to make sure you didn't get a NULL
pointer back.
At the end, you should free
the memory you've malloc
ed with
free(lines);
Upvotes: 3
Reputation: 17557
You can write a for-loop as:
char * lines[1000];
int i = 0;
for (i = 0; i < 1000; i++)
{
lines[i] = (char*)malloc(100 * sizeof(lines));
}
Don't forget to free-up the memory pointed by all the pointers
for (i = 0; i < 1000; i++)
{
free(lines[i])
}
Upvotes: 1
Reputation: 500157
The simplest way is:
char lines[100][1000];
Alternatively:
char* lines[100];
int i;
for (i = 0; i < 100; i++) {
lines[i] = malloc(1000);
}
...
for (i = 0; i < 100; i++) {
free(lines[i]);
}
The latter is a bit more flexible in that -- with minor modifications -- it permits you to allocate a different amount of memory for every string.
Upvotes: 3