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.

2
  • char pRecord = record;...how exactly? Commented Feb 16, 2016 at 17:24
  • 2
    You are trying to set a char pointer to a char. Try: char* pRecord = record Commented Feb 16, 2016 at 17:25

4 Answers 4

2

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

char *pRecord = &record[0][0];
Sign up to request clarification or add additional context in comments.

2 Comments

That is exactly the same effect as saying char *pRecord = record; :)
@mikeyq6 You should get a type warning for that. Luckily char* can alias that, but other types can't.
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++ = ' ';

Comments

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?

Comments

0
char (*pRecord)[COLS];
pRecord = record;

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

pRecord == *pRecord

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.