Search code examples
cmemorymemory-address68hc11

Reading memory address's in c using user inputted hex values


The aim is to allow the user to input a memory address (in Hex) and print out the contents of the address.

The code is running on the Motorola 68HC11.

So far i am able to read memory addresses using hard coded values:

void displayMemory(){
    char *p = (char*)0x5000;
    printf("Address Ascii: %s\n",p);
}

However i have tried multiple ways of using data input from the user such as:

void displayMemory(char *arr){
    char *p = arr;
    printf("Address Ascii: %s\n",p);
}

^^ where the *arr is the inputted hex value. Such as: 40a

I have also tried hard coding the hex value as a char array like:

void displayMemory(){
    char *p = "0x5000";
    printf("Address Ascii: %s\n",p);
}

This also did not work and gave me a different memory address.

Any ideas would be greatly appreciated, i am probably being very stupid!

UPDATED: how the function is called

char *arr;
arr = malloc(size * sizeof(char));
if(arr){
    strncat(arr, &userInput[3], size);
    displayMemory(arr);
}else{
    return 0;
}

userInput is : dm 40a size is: length of the number part of userInput in this case 3


Solution

  • You were about to find the solution yourself. If you input an address into a char array, for example with:

    char address[16];
    printf("Enter address in hexa: ");
    scanf("%15", address);
    

    and type 40a into it, address will point to the following character array: { '4', '0', 'a', '\0', ...} what lies after the terminating null is irrelevant. Extactly like in char *p = "0x5000"; p points to the (non modifiable because litteral) character array { '0', 'x', '5', '0', '0', '0', '\0'}`. Assuming ASCII, it gives { 0x34, 0x30, 0x41, 0, ...} in first case, and { 0x30, 0x78, 0x35, 0x30, 0x30, 0x30, 0} in second one. In either case, this exist at an arbitrary address unrelated to the value.

    And what works is when the address is the expected value. So you need to read the address as an integer value, and then convert it to a char pointer

    int address;
    scanf("%i", &address);
    char *p = (char *) address;    // NOT &address!