无法在 char 指针数组中打印指针地址

标签 c arrays pointers

我正在制作一个 RAM eater 程序,它在一个 while 循环中分配 64MB,直到它填满请求的数量,同时打印每个循环分配的内存地址。它在内存分配方面起作用,但不打印地址

我将粘贴所有代码,以便您可以跟踪变量的来源,并注释掉不起作用的行:

void eatRAM()
{
    int pCount = 0,
        input = 0,
        megaByte = 1048576;

    unsigned long long toEat = 0,
                       eaten = 0,
                       i = 0,
                       allocFragments = 64 * (unsigned long long) megaByte;

    puts("How much RAM do you want to eat? (in Mega Bytes)");
    printf("\n>> MB: ");
    scanf("%d", &input);

    if(input < 64)
    {
        allocFragments = input;
    }

    toEat = (unsigned long long)(input * megaByte);

    char * pMemory[toEat / allocFragments];

    printf("\n\nTotal to eat: %llu Bytes\n", toEat);

    do
    {
        pMemory[pCount] = malloc(allocFragments);
        if(pMemory[pCount] != NULL)
        {



            //NEXT LINE PRINTS: 
            // < a lot > Bytes were allocated succesfully in 0x00000000
            printf("%llu Bytes were allocated succesfully in 0x%p\n", allocFragments, pMemory[pCount]);





            for(i = 0; i < allocFragments; i++)
            {
                pMemory[pCount][i] = 'x';
            }
            pCount++;
            eaten += allocFragments;
        }
        else
        {
            puts("\nThere was an error trying to allocate memory. Finishing eating loop\n");
            break;
        }

    }
    while (pMemory[pCount] != NULL && eaten < toEat);

    puts("----------------------------------");
    printf("Total eaten: %llu Bytes\n", eaten);
    puts("Check your task manager!\n");

}

在那一行中,我尝试在 pMemory[pCount] 之前使用 &, *,但未能找到打印该地址的方法。

最佳答案

你有声明:

unsigned long long … allocFragments = 64 * (unsigned long long) megaByte;

还有 printf() 的调用:

printf("%li Bytes were allocated succesfully in 0x%p\n", allocFragments, pMemory[pCount]);

使用这段代码,您的问题是您将 unsigned long long(8 字节)传递给 printf(),但告诉它打印 long(4 个字节),因此它使用您提供的一些信息,但将其余信息(主要是零)保留为内存指针的一部分。

由于您正在使用 MiB 和 GiB 内存,并且您声称您正在为您的空指针获取 00000000,您可能在 32 位系统上,因此您有4 字节指针,您正在打印的指针实际上是 allocFragments 中更重要部分的零字节。

更新 printf() 现已更新为:

printf("%lli Bytes were allocated successfully in 0x%p\n", allocFragments, pMemory[pCount]);

理论上,这应该可以解决问题。 …还有一个comment它做到了!......

顺便说一句,如果您使用 GCC 作为编译器,它应该会警告您格式和要打印的值之间的类型不匹配。如果不是,则说明您没有正确使用它可以提供的警告。我通常使用这些选项进行编译——有时会打开一些额外的选项。

gcc -std=c11 -g -O3 -Wall -Wextra -Werror -Wmissing-prototypes \
    -Wstrict-prototypes -Wold-style-definition …

关于无法在 char 指针数组中打印指针地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34015189/

相关文章:

c - 如何打印字符**

Javascript将对象插入数组

javascript - 操作对象数组以获得唯一数据

C Void指针问题

c++ - vector 作为函数的参数 (int**)

c - 为什么选择报告读取文件描述符不断准备就绪?

c - C 中的对齐属性

php - 如何将数组与标识符合并?

c++ - Qt 中的 QPointer、QSharedPointer 和 QWeakPointer 类有什么区别?

c - Eclipse CDT 和 getch()