user533507
user533507

Reputation:

Is it possible to still address the individual elements of an array via a pointer?

I am trying to write a program that will mutliply two numbers, but output the result in binary, showing the calculation (i.e. shifting the rows). I'm storing the binary numbers as an array of 32 characters, and each element is either 1 or 0.

I have a function that will convert decimal to binary character array, but then my array only exists within the function, but I need to use the array within another function and also within main. I was thinking it might be possible to use pointers to change the value of the array in main from within my converter function, so then the array will exist in main and can be used in other functions. Is this possible?

I've declared two pointers to character arrays:

char (*binOne)[32];
char (*binTwo)[32];

if I pass the pointer as a parameter to the function, can I still access each element? Sorry if I'm not making much sense here.

Upvotes: 1

Views: 120

Answers (3)

KCH
KCH

Reputation: 2854

In C, most of the time array behaves like pointer to its first element, so what you probably want to do is:

void foo(char* arr){
  //some stuff, for example change 21-th element of array to be x
  arr[20] = 'x';
}

int main(){
  char binOne[32];
  char binTwo[32];

  // change array binOne
  binOne[20] = 'a';

  foo(binOne);

  // now binOne[20] = 'x'

  foo(binTwo);

  // now binTwo[20] = 'x'
}

Upvotes: 2

AusCBloke
AusCBloke

Reputation: 18512

A continuation of what I added as a comment:

In C, if you want to modify/return an array, you'll do that by passing a pointer to it as an argument. For example:

int toBinary(char *buff, int num) { /* convert the int, return 1 on success */ }
...
char buff[32];
toBinary(buff, 9001);

In C, an array's name is it's address, it's the address of the first element:

buff == &buff == &buff[0]

Upvotes: 1

Bort
Bort

Reputation: 2491

Yes, this is possible. But you only need a pointer to the array not an array of pointers. You need to prototype like e.g.

void int_to_arr(int n, char *arr);
void arr_to_int(int *n, char *arr);

in main(){

   char *binarr = calloc(32, sizeof(char));
   int n = 42;
   int_to_arr(n, binarr);
}

void int_to_arr(int n, char *arr)
{
   //do you conversion
   //access array with 
   // arr[i]
}

void arr_to_int(int *n, char *arr)
{
   //do you conversion
   //access array with 
   // *n = result;

}

Upvotes: 0

Related Questions