Отображение из шестнадцатеричного в символьное с использованием условного оператора

Итак, в основном я хочу, чтобы моя программа отображала следующее:
(адрес памяти) (16 байтов шестнадцатеричных значений) (эти шестнадцатеричные значения в символах)
Теперь у меня правильный формат, за исключением того, что следующая строка всегда возвращает '0' и поэтому символы вообще не отображаются:
printf("%c", isgraph(*startPtr)? *startPtr:'.');
Наконец, я думаю, что правильно использую srand и rand, но мой массив не заполняется случайным материалом. Всегда одно и то же.
В любом случае, вот код:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>

void DumpMem(void *arrayPtr, int numBytes);
void FillMem(void *base, int numBytes);

int main(void)
{
    auto int numBytes;
    auto double *doublePtr;
    auto char *charPtr;
    auto int *intPtr;

    srand(time(NULL));
    // Doubles
    printf("How many doubles? ");
    scanf("%d", &numBytes);
    doublePtr = malloc(numBytes * sizeof(*doublePtr));

    if (NULL == doublePtr)
    {
        printf("Malloc failed!");
    }

    printf("Here's a dynamic array of doubles... \n");
    FillMem(doublePtr, numBytes * sizeof(*doublePtr));
    DumpMem(doublePtr, numBytes * sizeof(*doublePtr));
    // Chars
    printf("\nHow many chars? \n");
    scanf("%d", &numBytes);
    charPtr = malloc(numBytes * sizeof(*charPtr));

    if (NULL == charPtr)
    {
        printf("Malloc failed!");
    }

    printf("Here's a dynamic array of chars... \n");
    FillMem(charPtr, numBytes * sizeof(*charPtr));
    DumpMem(charPtr, numBytes * sizeof(*charPtr));
    // Ints
    printf("\nHow many ints? \n");
    scanf("%d", &numBytes);
    intPtr = malloc(numBytes * sizeof(*intPtr));

    if (NULL == intPtr)
    {
        printf("Malloc failed!");
    }

    printf("Here's a dynamic array of ints... \n");
    FillMem(intPtr, numBytes * sizeof(*intPtr));
    DumpMem(intPtr, numBytes * sizeof(*intPtr));

    // Free memory used
    free(doublePtr);
    free(charPtr);
    free(intPtr);
}

void DumpMem(void *arrayPtr, int numBytes)
{
    auto unsigned char *startPtr = arrayPtr;
    auto int counter = 0;
    auto int asciiBytes = numBytes;

    while (numBytes > 0)
    {
        printf("%p ", startPtr);

        for (counter = 0; counter < 8; counter++)
        {
            if (numBytes > 0)
            {
                printf("%02x ", *startPtr);
                startPtr++;
                numBytes--;
            }
            else
            {
                printf("   ");
            }
        }

        printf(" ");

        for (counter = 0; counter < 8; counter++)
        {
            if (numBytes > 0)
            {
                printf("%02x ", *startPtr);
                startPtr++;
                numBytes--;
            }
            else
            {
                printf("   ");
            }
        }

        printf(" |");
        // 'Rewind' where it's pointing to
        startPtr -= 16;

        for (counter = 0; counter < 16; counter++)
        {
            if (asciiBytes > 0)
            {
                printf("%c", isgraph(*startPtr)? *startPtr:'.');
                asciiBytes--;
            }
            else
            {
                printf(" ");
            }
        }
        puts("| ");
    }
}

void FillMem(void *base, int numBytes)
{
    auto unsigned char *startingPtr = base;

    while (numBytes > 0)
    {
        *startingPtr = (unsigned char)rand;
        numBytes--;
        startingPtr++;
    }
}

Почему я не получаю случайные значения внутри массива? И почему мой условный оператор всегда 'false'?


person relapsn    schedule 16.10.2013    source источник


Ответы (1)


Вы заполняете свой массив младшим байтом указателя функции на rand, а не случайным числом. Вам нужно вызвать функцию:

    *startingPtr = (unsigned char)rand();

Вы также не увеличиваете startPtr при печати данных символов. Вам нужно startPtr++ там:

        if (asciiBytes > 0)
        {
            printf("%c", isgraph(*startPtr)? *startPtr:'.');
            startPtr++;
            asciiBytes--;
        }

В нынешнем виде ваша программа просто печатает первый байт снова и снова, а затем переходит к следующей строке и печатает идентичный предыдущей строке.

person Carl Norum    schedule 16.10.2013
comment
Я чувствую себя глупо, ха-ха. Спасибо. Однако это не меняет того факта, что символы не отображаются в последнем столбце. - person relapsn; 17.10.2013
comment
Ничего себе, я не могу поверить, что я упустил из виду эти две вещи. Большое спасибо! - person relapsn; 17.10.2013