Spoons
Spoons

Reputation: 43

C pointer in char array

I am trying to understand if my solution to a problem I have is possible, I want to add a pointer to an array member of a stack allocated array so that the array member is dynamically changeable.

Has to be an unsigned char as this is a comms buffer.

int main() {
    unsigned char *var;
    unsigned char test[] = {*var, 0x34, 0x56, 0x78};
    *var = 0x12;
    printf("%x %x %x %x %x", *var, test[0],test[1],test[2],test[3]);
    *var = 0xff;
    printf("%x %x %x %x %x", *var, test[0],test[1],test[2],test[3]);
}

Thanks for any answers either yay or nay.

edit: Thanks for all the suggestions, I had looked at using array indexes before trying to find a different method. The issue is that there is no way to know the array index as the array that is being edited is concatenated to form a larger array so the index changes which is why I wanted to use a variable.

Upvotes: 0

Views: 69

Answers (2)

0___________
0___________

Reputation: 68023

The problem you have is that you do not understand what the pointer is.

    unsigned char* var;
    unsigned char test[] = { 0x00, 0x34, 0x56, 0x78 };

This invokes undefined behaviour. var is the pointer to char but does not point anywhere (it is not initialized or saying other way it has no assigned reference). The second definition simple takes the char value referenced by this pointer (which does not point to any valid character) and places this value as the first element of the array test. The array itself does not hold any information that about the sources of the data stored.

To make this code working you need to assign the pointer with the reference of the first element of the array.

int main(void)
{
    unsigned char test[] = { 0x00, 0x34, 0x56, 0x78 };
    unsigned char* var = test;  /* or &test[0] */

    *var = 0x12;
    printf("%x %x %x %x %x\n", *var, test[0], test[1], test[2], test[3]);

    *var = 0xff;
    printf("%x %x %x %x %x\n", *var, test[0], test[1], test[2], test[3]);
}

Minor problem: your main declaration is invalid. It has to be int main(void)

Upvotes: 1

fpiette
fpiette

Reputation: 12322

You have it almost. Try this:

int main()
{
    unsigned char* var;
    unsigned char test[] = { 0x00, 0x34, 0x56, 0x78 };
    var = &test[0];  // Makes var point to the first test[] item
    *var = 0x12;
    printf("%x %x %x %x %x\n", *var, test[0], test[1], test[2], test[3]);
    *var = 0xff;
    printf("%x %x %x %x %x\n", *var, test[0], test[1], test[2], test[3]);
}

Upvotes: 2

Related Questions