有一件事总让我困惑,角色指针.经过四年多的努力,我再次陷入困境.
以上面提到的情况为例.为什么char指针会以这种方式运行?当指针指向什么都没有时,我们怎么能直接解决指针的内容呢?或者它就像char指针存储除地址之外的东西!
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* charPtr="I cant understand why";
int* intPtr=60;
printf("%d\n", intPtr); //displays 60
printf("%p\n", intPtr); // displays the hex value of 60
printf("%s\n", charPtr); // displays the wh0le string
printf("%p\n", charPtr); // displays the start address of the string
return 0;
Run Code Online (Sandbox Code Playgroud)
}
接下来是int指针,它如何接受值60以及它存储在何处?
抛开char指针和malloc,我认为指针的基本思想是得到一个指向的地址!
为什么这些案件
*intptr = 60 ; // should be setting the pointee's value to 60
intptr = 60 ; // sets the address
Run Code Online (Sandbox Code Playgroud)
抛出编译错误
int* intPtr=60; …Run Code Online (Sandbox Code Playgroud) 我们如何通过结构指针获取数组元素的地址?
我有一个示例代码如下:
#include<stdio.h>
#include<string.h>
typedef struct {
int mynam ;
} transrules;
typedef struct {
int ip ;
int udp;
transrules rules[256];
}__attribute__ ((__packed__)) myudp;
myudp udpdata ;
myudp* ptrudp = &udpdata ;
int main(){
memset (&udpdata , 0 ,sizeof(udpdata));
ptrudp->ip = 12 ;
ptrudp->udp = 13 ;
ptrudp->rules[0].mynam = 15 ;
printf("%d",ptrudp->rules[0].mynam);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的函数希望将rules [0]的地址作为参数传递。是否可以打印rule [0]的地址,或者实际上是否可以打印任何rue [n]的地址?
#include <stdio.h>
int main(void) {
int TEST_HB[10];
memset(TEST_HB,'9', sizeof( TEST_HB));
printf("%c\n",TEST_HB[9]);
printf ("TEST_HB[10]=%d\n",sizeof( TEST_HB[40])); // shows 4
printf ("Arraysize=%d\n",(sizeof(int)*10)); // gets the expectected results
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我相信sizeof(myArray)应该以字节为单位返回数组的总大小.但是,为什么sizeof( TEST_HB[40])在没有定义时会返回4?
我有一个代码如下:
int main(void)
{
char mychar = 'd';
int *ptr = malloc(sizeof(*ptr)) ;
*ptr = (char) 'c' ; // *ptr = (char*) 'c'; Gives the exact same result
printf("%c\n",*ptr);
memset(ptr,mychar,sizeof(*ptr));
printf("%c\n",*ptr);
free(ptr);
printf("%c\n",*ptr);
return 0 ;
}
Run Code Online (Sandbox Code Playgroud)
代码为指针样式转换和数据类型转换提供相同的结果.
应该使用哪两种风格中的哪一种或被认为是一种好的做法?为什么?
*ptr = (char) 'c' ;
*ptr = (char*) 'c';
Run Code Online (Sandbox Code Playgroud)