我的代码是:
#include <stdio.h>
#include <string.h>
void main()
{
char string[10];
int A = -73;
unsigned int B = 31337;
strcpy(string, "sample");
// printing with different formats
printf("[A] Dec: %d, Hex: %x, Unsigned: %u\n", A,A,A);
printf("[B] Dec: %d, Hex: %x, Unsigned: %u\n", B,B,B);
printf("[field width on B] 3: '%3u', 10: '%10u', '%08u'\n", B,B,B);
// Example of unary address operator (dereferencing) and a %x
// format string
printf("variable A is at address: %08x\n", &A);
Run Code Online (Sandbox Code Playgroud)
我在linux mint中使用终端编译,当我尝试使用gcc编译时,我收到以下错误消息:
basicStringFormatting.c: In function ‘main’:
basicStringFormatting.c:18:2: warning: …Run Code Online (Sandbox Code Playgroud) 为什么以下代码每次输出相同的内存位置?
int x;
for (x = 0; x < 10; x++) {
int y = 10;
printf("%p\n", &y);
}
Run Code Online (Sandbox Code Playgroud)
我认为每次运行for循环时内存位置都应该改变,变量是新的.
在这段代码中
#include <stdio.h>
int main ()
{
int i;
for (i=0;i<5; i++)
{
int h;
printf("%p \n",&h);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
每个循环中的输出相同.正如C中的其他问题For循环局部变量所述,为什么每次在本地范围内为变量分配相同的地址?这是因为编译器优化而发生的.我想找到一种方法来阻止这种优化,以便每次声明变量h时都有不同的地址.我知道我可以使用malloc并每次分配不同的堆内存,但我想找到一个使用堆栈内存的解决方案.gcc是否有禁用此优化的标志?