0

Why is the passing of char array not showing? The location of the pointer is passed to a function.

char plaintext[] = {
         0xCD,  0x76,  0x43,  0xF0,
         0x72,  0xA4,  0xA0,  0x82,
}

Given

 void displayArray(char** plaintext, int size) {
 // int newSize = sizeof(**plaintext);
 int i;

 for(i=0; i < size; ++i) {
     printf("%02X ", (0xff & *plaintext[i]));
    if (((i+1)% 8) == 0)    // as index starts from 0, (i+1)
        printf("\n");
 }
}

in main()

        char* plaintextCopy;
        plaintextCopy = (char*) malloc(numberOfItems*sizeof(char));

        memcpy(plaintextCopy, plaintext, numberOfItems);

        displayArray(&plaintextCopy, numberOfItems);
2
  • How are you setting numberOfItems? I don't think memcpy() and your displayArray() use the same definition. Commented Mar 23, 2014 at 19:54
  • int numberOfItems = sizeof(plaintext); printf("Number of items: %d \n", numberOfItems); Commented Mar 23, 2014 at 20:01

1 Answer 1

1

Based on your code :

void displayArray(char** plaintext, int size)
{
    int i;

    for(i=0; i < size; i++) 
    {
        printf("%02X ", (0xff & (*plaintext)[i]));
        if(((i+1)% 8) == 0)    // as index starts from 0, (i+1)
            printf("\n");
    }
}

int main(void)
{


    char plaintext[] = {
         0xCD,  0x76,  0x43,  0xF0,
         0x72,  0xA4,  0xA0,  0x82,
    };

    int numberOfItems = sizeof(plaintext);

     char* plaintextCopy;
     plaintextCopy = (char*) malloc(numberOfItems*sizeof(char));

     memcpy(plaintextCopy, plaintext, numberOfItems);

     displayArray(&plaintextCopy, numberOfItems);

    return 0;
}

It outputs :

CD 76 43 F0 72 A4 A0 82

Also, if you're sending an array that you want to display or change the values of, you don't need to send a double pointer to a function. A regular pointer would do. You should only use double pointers if the original array changes it's location in memory, that is, it's getting a new pointer after the function returns.

Sign up to request clarification or add additional context in comments.

4 Comments

try with this modification.
Ok. I have tested the code and I will include it fully in the answer shortly.
What if I want to calculate the size in the call function? eg. ` void displayArray(char** plaintext) { int i; int size = sizeof(*plaintext);` ?
It will return 4 since that's the size of (char *) i.e. a pointer to char. sizeof() only works on char[]. You can either keep the length in a separate variable or hold it in the array at the start or at the end. Or you can use a 0x00 to show that it's the end of the array.

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.