gameboy
gameboy

Reputation: 1595

C dynamic string array

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

Answers (4)

Joshua Green
Joshua Green

Reputation: 1575

It looks like you want an array strings, each string holding at most 1000 characters.  There are some issues with your code.

  1. You've declared an array of char *s but what you really want is a pointer to an array of chars.  For that, your declaration should be

    char (*lines)[1000];
    
  2. 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];
    
  3. 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 chars, *lines is a char[1001].  Remember to make sure you didn't get a NULL pointer back.

  4. At the end, you should free the memory you've malloced with

    free(lines);
    

Upvotes: 3

cpx
cpx

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

chutsu
chutsu

Reputation: 14093

Why don't you create a 2 dimensional array?

Upvotes: 0

NPE
NPE

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

Related Questions