本文介绍了需要帮助理解C中的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我实际上非常理解指针,我只是在下面发布的代码中的一件事情上感到困惑。不仅是指针而是写(unsigned int),然后是变量名或函数。代码如下,我评论了我需要解释的内容,这是我从教科书中得到的代码。
I actually understand pointers very well, I am just confused mostly on one thing in the code i posted below. Not only pointers but writing (unsigned int) then a variable name or function after it. The code is below, I commented what i need explaining, this is code I am getting from a text book.
#include <stdio.h>
#include <ctype.h>
typedef unsigned char BYTE;
int main(void)
{
unsigned int addr;
int i , n;
BYTE* ptr;
printf("Address of main function: %x\n" , (unsigned int) main); //why is unsigned int here?
printf("Address of addr variable: %x\n" , (unsigned int) &addr);//and here also?
printf("\nEnter a (hex) address: ");
scanf("%x" , &addr);
printf("Enter Number of bytes to view: ");
scanf("%d" , &n);
printf("\n");
printf("Address Bytes Characters\n");
printf("------- -------- -----------");
ptr = (BYTE*)addr;//is ptr a conversion from int to BYTE*? I do not understand this.This is what i need explaining most with
for(; n > 0;n -= 10)
{
printf("%8X " , (unsigned int) ptr); //what does unsigned int mean in front of ptr and why is it needed?
for(i = 0; i < 10 && i < n; i++)
printf("%.2X ", *(ptr + i));
for(; i < 10; i++)
printf(" ");
printf(" ");
for(i = 0; i <10 && i < n ; i++)
{
BYTE ch = *(ptr + i);
if(!isprint(ch))
ch ='.';
printf("%c" , ch);
}
printf("\n");
ptr += 10;
}
return 0;
}
推荐答案
#include <stdio.h>
#include <ctype.h>
typedef unsigned char BYTE;
int main(void)
{
unsigned int addr;
int i , n=50;
BYTE* ptr;
printf("Address of main function: %x\n" , (unsigned int) main); // unsigned int because we wish to print the adddress of main as an unsigned int
printf("Address of addr variable: %x\n" , (unsigned int) &addr);// unsigned int because we wish to print the adddress of addr as an unsigned int
// printf("\nEnter a (hex) address: ");
//scanf("%x" , &addr);
// printf("Enter Number of bytes to view: ");
//scanf("%d" , &n);
addr = (unsigned int) main; // Take the address of main
printf("\n");
printf("Address Bytes Characters\n");
printf("------- -------- -----------\n");
ptr = (BYTE*)addr; // Assign addr to pointer. To do this we need to make a BYTE * pointer out of addr using a cast.
for(; n > 0; n -= 10)
{
printf("%8X " , (unsigned int) ptr); // ptr is a BYTE * and we wish to print its value as an unsigned int (the address)
for(i = 0; i < 10 && i < n; i++)
printf("%.2X ", *(ptr + i));
for(; i < 10; i++)
printf(" ");
printf(" ");
for(i = 0; i <10 && i < n ; i++)
{
BYTE ch = *(ptr + i);
if(!isprint(ch))
ch ='.';
printf("%c" , ch);
}
printf("\n");
ptr += 10;
}
return 0;
}
这篇关于需要帮助理解C中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!