gpt4 book ai didi

C 程序仅由于格式说明符而显示错误

转载 作者:行者123 更新时间:2023-11-30 19:27:23 25 4
gpt4 key购买 nike

由于我在 for 循环中打印数组地址时使用的格式说明符,该程序显示错误。如果我使用除 %p 之外的任何格式说明符来打印地址,例如 %ld、%u、%d 等,则会显示如下错误:

prog.c: In function 'main':
prog.c:18:10: warning: format '%ld' expects argument of type 'long int', but argument 3 has type 'int *' [-Wformat=]
printf("Address arr[%d] is %ld\n", i, &arr[i]);
^

这是我的代码:

 // C program to demonstrate that array elements are stored 
// contiguous locations

#include <stdio.h>
int main()
{
// an array of 10 integers. If arr[0] is stored at
// address x, then arr[1] is stored at x + sizeof(int)
// arr[2] is stored at x + sizeof(int) + sizeof(int)
// and so on.
int arr[5], i;

printf("Size of integer in this compiler is %lu\n", sizeof(int));

for (i = 0; i < 5; i++)
// The use of '&' before a variable name, yields
// address of variable.
printf("Address arr[%d] is %ld\n", i, &arr[i]);

return 0;

我无法理解为什么在这里使用 %p 以及我可以使用什么来使我的程序没有错误

最佳答案

该标准提供了“%p”用于打印指针地址,并且它期望提供的类型为void*。您可以重新编写代码以正确使用“%p”,如下所示:

#include <stdio.h> 

int main (void)
{
int arr[5], i;

printf ("Size of integer in this compiler is %lu\n", sizeof(int));

for (i = 0; i < 5; i++)
printf ("Address arr[%d] is %p\n", i, (void*)&arr[i]);

return 0;
}

示例使用/输出

$ ./bin/ptraddrarr
Size of integer in this compiler is 4
Address arr[0] is 0x7ffe251cac50
Address arr[1] is 0x7ffe251cac54
Address arr[2] is 0x7ffe251cac58
Address arr[3] is 0x7ffe251cac5c
Address arr[4] is 0x7ffe251cac60

不推荐,但您可以使用“0x%lx”格式说明符来获得相同的输出,例如

        printf ("Address arr[%d] is 0x%lx\n", i, (unsigned long)&arr[i]); 

但是,不要使用为此目的明确提供的正确格式说明符。

关于C 程序仅由于格式说明符而显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55791627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com