char * pp和(char *)p之间的区别? [英] Difference between char *pp and (char*) p?

查看:128
本文介绍了char * pp和(char *)p之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的练习遇到问题,我必须解释在C中运行指针的情况.

I am having a problem with my exercise in which I have to explain the running of pointers in C.

您能解释一下 char * pp (char *)p 以及输出给我的有什么区别吗?

Can you explain what is the differences between char *pp and (char*) p and the outputs to me?

#include <stdio.h>
#include <stdlib.h>

/*
 * 
 */
int main(int argc, char** argv) {

    int n=260, *p=&n;
    printf("n=%d\n", n);
    char *pp=(char*)p;
    *pp=0;
    printf("n=%d\n",n);
    return (EXIT_SUCCESS);
}

n = 260
n = 256

n=260
n=256

对于我犯的错误,我感到非常抱歉!希望你们能帮助我.

I'm so sorry for the mistake I've done! Hope you guys can help me.

推荐答案

char * pp 将变量 pp 声明为指向 char 的指针- pp 将存储 char 对象的地址.

char *pp declares the variable pp as a pointer to char - pp will store the address of a char object.

(char *)p cast表达式-意思是将 p 的值作为 char * ".

(char *)p is a cast expression - it means "treat the value of p as a char *".

p 被声明为 int * -它存储 int 对象的地址(在这种情况下,的地址> n ).问题是 char * int * 类型不兼容 -您不能将一个直接分配给另一个 1.您必须使用强制转换将值转换为正确的类型.

p was declared as an int * - it stores the address of an int object (in this case, the address of n). The problem is that the char * and int *types are not compatible - you can’t assign one to the other directly1. You have to use a cast to convert the value to the right type.



  1. 指向不同类型的指针本身就是不同类型,并且不必具有相同的大小或表示形式.一个例外是 void * 类型-专门将其引入为通用"指针类型,并且在 void * 之间进行分配时无需显式转换和其他指针类型.
  1. Pointers to different types are themselves different types, and do not have to have the same size or representation. The one exception is the void * type - it was introduced specifically to be a "generic" pointer type, and you don’t need to explicitly cast when assigning between void * and other pointer types.

这篇关于char * pp和(char *)p之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆