Reducing Repeated code for arrays

J

JellyBum

Hey there, having a bit of a problem trying to acheive something..

Ive got 2 arrays, ArrayA, ArrayB both are of type char with [5][7]
dimensions.

Ive got code in a function, which does
if(ArrayA[x][y] == 'A') { // do something }

but i also have
if(ArrayB[x][y] == 'A') { // do something }

so for each array im doubling it.

Im wondering, if i could do, if(SOMETHING[x][y] ==

and then reference the arrayname in SOMETHING

Any ideas please?

Thanks
 
R

Rob van der Leek

Ive got 2 arrays, ArrayA, ArrayB both are of type char with [5][7]
dimensions.

Im wondering, if i could do, if(SOMETHING[x][y] ==
and then reference the arrayname in SOMETHING

You can access both arrays via a pointer. Your pointer must have the
type:
char (*pArray)[7]

if you want to be able to point it to arrays of type:

char ArrayA[5][7]

then you can say:

pArray = ArrayA; // or: pArray = ArrayB
if (pArray[x][y] == ...

Regards,
 
M

Mike Wahler

JellyBum said:
Hey there, having a bit of a problem trying to acheive something..

Ive got 2 arrays, ArrayA, ArrayB both are of type char with [5][7]
dimensions.

Ive got code in a function, which does
if(ArrayA[x][y] == 'A') { // do something }

but i also have
if(ArrayB[x][y] == 'A') { // do something }

so for each array im doubling it.

Im wondering, if i could do, if(SOMETHING[x][y] ==

and then reference the arrayname in SOMETHING

Any ideas please?

Use a function.

#include <stdio.h>
#include <stdlib.h>

void foo(char (*arr)[7])
{
size_t row = 0;
size_t col = 0;
char value = 'A';

printf("[%ld][%ld]", (unsigned long)row, (unsigned long)col);

if(arr[0][0] == value)
printf(" == ");
else
printf(" != ");

printf("'%c'\n", value);
}

int main()
{
char ArrayA[5][7] = {'A'};
char ArrayB[5][7] = {'B'};

printf("ArrayA");
foo(ArrayA);

printf("ArrayB");
foo(ArrayB);

return 0;
}


-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,999
Latest member
MakersCBDGummiesReview

Latest Threads

Top