1

I wanted to convert two dimensional array to a one dimension (array linearization ) by using a pointer and setting it to a particular character. Here is the code:

#define COLS 20
#define ROWS 10

void convert(void)
{

    char record[ROWS][COLS] = { 0 };

    char *pRecord = record;

    int i = 0;

    for (i = 0; i < (ROWS*COLS); i++)
    {
        *(pRecord++) = ' ';

    }

}

However, I am getting a compiler error in initializing the pointer to char array. I 'vd edited the code i.e it will be *pRecord, previously it was only pRecord. Need some help in understanding the error and if possible some suggestions to fix it.

zam
  • 181
  • 2
  • 6
  • 18

4 Answers4

2

May I suggest you define the pointer as a pointer? This compiles cleanly on my machine:

char *pRecord = &record[0][0];
user1683793
  • 1,213
  • 13
  • 18
1

Your loop is implementing the equivalent of memset(record, ' ', sizeof(record)). A manual implementation would roughly look like:

char *pRecord = (void *)record;
size_t len = sizeof(record);
while (len--) *pRecord++ = ' ';
jxh
  • 69,070
  • 8
  • 110
  • 193
1

If you want to Convert two dimensional array to a one dimension, check this idea:

#include<stdio.h>
#define COLS 20
#define ROWS 10

void convert(void)
{
   int i,j;
   char  *pRecord ;
   char newArray [COLS * ROWS];
   pRecord  = newArray;
   char record[ROWS][COLS] = { 0 };

    for ( i = 0 ; i <  ROWS ; i++)
      for ( j = 0; j < COLS ; j++){
        *pRecord = record[i][j]; 


      }

}

Maybe this post will serve How do pointer to pointers work in C?

Community
  • 1
  • 1
pazthor
  • 11
  • 3
0
char (*pRecord)[COLS];
pRecord = record;

Though, in the case of array, that will turn out in this way.

pRecord == *pRecord
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
nariuji
  • 288
  • 1
  • 6