简体   繁体   English

C:未初始化的char指针并打印出地址

[英]C : uninitialized char pointer and print out the address

I have some local pointers and before which I am given two global pointers. 我有一些局部指针,在此之前有两个全局指针。

My task is to print out every byte between the two global pointers +/- 32. And the local pointers will be different because I will mark it different than global pointers. 我的任务是打印出两个全局指针+/- 32之间的每个字节。局部指针将有所不同,因为我将其标记为与全局指针不同。

And my question is how to initialize at first every byte between the two pointers? 我的问题是如何首先初始化两个指针之间的每个字节? The following is my try but not working: 以下是我的尝试,但不起作用:

// global scope
char * minimum_ptr, * maximum_ptr;

int main()
// inside main function
char * temp_ptr = minimum_ptr-32;
char * add_ptr = minimum_ptr-32;
while (temp_ptr != maximum_ptr+32) {
  add_ptr = NULL;
  temp_ptr++;
}

// getting errors
printf("%p", (char *)(minimum_ptr));
printf("%p", (char *)(minimum_ptr+1));

I corrected it, but still confusing sorry. 我已更正,但仍然使您感到困惑。 I am confused too. 我也很困惑。 All I want, is to print out the address between the two pointers, minimum_ptr-32 and maximum_ptr+32, and minimum_ptr and maximum_ptr are not initialized yet but I might need so if I need to. 我想要的是打印出两个指针之间的地址,minimum_ptr-32和maximum_ptr + 32,并且minimum_ptr和maximum_ptr尚未初始化,但是如果需要的话,可能需要这样做。

Addition: I want to initialize all of them first and do some assignment after then so that I can print out everything between and see what and where has been assigned. 另外:我想先初始化它们,然后再进行一些赋值,以便我可以打印出它们之间的所有内容,并查看分配了什么和在哪里。 Thanks 谢谢

First of all you need to be sure that the pointers are showing the correct addresses. 首先,您需要确保指针显示正确的地址。 Pointers are not different then arrays (yes they are different but..), so you may assume them to be arrays. 指针与数组没什么不同(是的,它们是不同的,但是..),因此您可以假定它们是数组。 I assume that the maximum_ptr's address is greater than the minimum_ptr's address. 我假设maximum_ptr的地址大于minimum_ptr的地址。

uint dist = maximum_ptr - minimum_ptr;
for (int i = 0; i < dist; ++i) {
   minimum_ptr[i] = 'A';
}

or you might use std::fill 或者您可以使用std :: fill

std::fill(minimum_ptr, maximum_ptr, 'a');

http://www.cplusplus.com/reference/algorithm/fill/ http://www.cplusplus.com/reference/algorithm/fill/

you might adjust the pointer values 您可能会调整指针值

std::fill(minimum_ptr - 32, maximum_ptr + 32, 'a');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM