Peter Hwang
Peter Hwang

Reputation: 991

space allocation for a number of strings

Hi I am trying to get a space for storing a number of words. My plan is to use a two-dimension array, which stores a string. It looks like this:

pBuffer[0]---------->myBuffer[0][0] myBuffer[0][1]...
pBuffer[1]---------->myBuffer[1][0] myBuffer[1][1]...
..

However, it gets error and I am struggling to debug this. What's the problem?

1. Declaration

char myBuffer[255][255];
char* pBuffer[255];

2. Usage

char* pBuffer[i] = &myBuffer[i][0];
pStream->cmdArray[i].u.word = &pBuffer[i];
strcpy(*pStream->cmdArray[i].u.word, infix_string);
i++;

3. Error & Warning

error: variable-sized object may not be initialized
  char* pBuffer[i] = &myBuffer[i][0];
  ^
warning: unused variable 'pBuffer' [-Wunused-variable]
   char* pBuffer[255];

Upvotes: 0

Views: 72

Answers (2)

kfsone
kfsone

Reputation: 24269

char* pBuffer[i] = &myBuffer[i][0];

Remove the leading "char*", the compiler thinks you're trying to declare a new variable called pBuffer which "shadows" the original definition of pbuffer.

char* pBuffer[255]; // declares pbuffer as an array of 255 char* pointers
char* pBuffer[i];   // illegal and, if it worked, would be a shadow declaration.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477358

Because you wrote something weird. It should just be pBuffer[i] = &myBuffer[i][0];, in a loop of course.

Upvotes: 1

Related Questions