This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Problems with pointer.

Hi,
I have the following chunk of code:
unsigned char code A[4]={3,'L','P','L'}
unsigbed char code B[3]={2,'P','P'}
If a customer by means of a keyboard, writes the letter A in a variable a pointer must point for the Array A[4], if instead writes the B letter, must point for the Array B. How can I realize this function with a Pointer?
Best regard
Antonello

  • unsigned char code A[4]={3,'L','P','L'};
    unsigned char code B[3]={2,'P','P'};
    
    char customerChar;
    unsigned char code *p;
    
    if (customerChar == 'A')
        p = A;
    else if (customerChar == 'B')
        p = B;

  • Quibble: the above code falls through with an undefined value for p if customerChar is neither A nor B. It should have another else for error handling, or perhaps a default value:

    p = A;
    if (customerChar == 'B')
        {
        p = B;
        }
    

    You might also make it a switch statement, (a matter of taste) which also gives you a nice place to put some error handling code:
    switch (customerChar)
        {
        case 'A' :
            p = A;
            break;
    
        case 'B' :
            p = B;
            break;
    
        default: // unexptected value for customer char
            // error handling code goes here
            p = NULL;
            break;
        }
    

    Interesting that you're using strings with an explicit length ("Pascal-style"). C strings are traditionally a series of characters terminated by the null character (0). Any of the standard library functions will expect the strings to be of the second form.