Search code examples
cpointerspass-by-reference

Unable to pass reference of array to method in C


I create a char array and want to pass a reference to it to a method which populates the array.

char binary[BYTE_LEN];
readBinaryInput(&binary);

The method is as follows.

void readBinaryInput(char *binaryString[]) {

    printf("Enter an 8-bit binary string.\n");
    int i;
    for(i = 0; i < BYTE_LEN; i++) {
        scanf("%s", binaryString[i]);
    }

}

When I run the program calling the method, I get the following errors.

warning: passing argument 1 of 'readBinaryInput' from incompatible pointer type [-Wincompatible-pointer-types]
readBinaryInput(&binary);

note: expected 'char **' but argument is of type 'char (*)[8]'
void readBinaryInput(char *binaryString[]) {

I thought I was passing an address (&binary) to the method for the pointer argument to point to. Why am I getting errors telling me that char ** is expected?


Solution

  • Try simply removing the & from &binary and the * from char *binaryString[].

    char binary[BYTE_LEN] is already a pointer (essentially equivalent to char*). It is a pointer to the first byte in your char array. Treat it as such.