How to show the starting address of some variables in C?

房东的猫 提交于 2019-12-06 15:39:32

In main :

print out the addresses of argc, argv - printf ("%d, %d", &argc, argv);

print out the starting address and end address of the command line arguments of this process - printf ("%d", (void *)argv);

print out the starting address and end address of the environment of this process - printf ("%d", (void *)environ);

print out the starting addresses of function main, f1, and f2 - printf ("%d %d %d", &main, &f1, &f2);

print out the addresses of global_x, global_y, global_array1, global_array2, global_pointer1, global_pointer2, global_float, global_double - just use the & operator in front of each variable whose address you want to print.

print out the addresses of string literals 10, "Hello, world!", "bye", 100.1 - printing addresses of string literals is not allowed.

In f1:

print out the addresses of x1, x2, x3, x4, x5, x6 - printf ("%d %d %d %d %d %d", &x1, &x2, &x3, &x4, &x5);

print out the addresses of f1_x, f1_y, f1_p1, f1_p2 - printf ("%d %d %d %d", &f1_x, &f1_y, f1_p1, f2_p2);

print out the address of the string literal "This is inside f1" - Taking address of a string literal is not allowed

In f2:

print out the address of x - printf ("%d", &x);

print out the addresses of f2_p, and f2_x - printf("%d", f2_p, &f2_x);

print out the starting address of the dynamically allocated memory - printf ("%d", f2_p);

f1 and f2 (without the (parameter) block) is the starting address of the function For better clarification. f2(x); calls the function int f2(int x) passing the parameter x. "f2" without the parenthesis is the address of function int f2(int x)

joke

To declare a string literal as per my lecturer's guidance -

char *p = "this is a string literal";

printf("address of variable p starts at %p\n",  &p));
printf("address of the string literal starts at %p\n", p);

For that you need the & operator. It takes the address of a variable

Some more info on pointer operators can be found here

to the starting address of a regular variable:

printf("%p", &variable);

These variables don't realy have an end address, but i think what you want is something like:

printf("%p", (&variable + 1));

which prints the next available address

If you want to see the address of a variable you need to use the & operator or the straight pointer (in the case of dynamically allocated memory).

int main(int argc, char *argv[]){  
   int * arr;
   int i = 0;
   arr = malloc(100 * sizeof(int));
   printf("dynamic array starts at: %#x and ends at: %#x\n",arr,arr+100);
   printf("static i is at: %#x\n",&i);
}

Output:

mike@linux-4puc:~> ./a.out 
dynamic array starts at: 0x804b008 and ends at: 0x804b198
static i is at: 0xbfc1f6d8
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!