Tag: 指针

转换指针不会产生左值。 为什么?

在这里发表我最有争议的答案之一后,我敢问几个问题,最终填补了我的知识空白。 为什么不将类型((type_t *) x)的表达式视为有效的左值,假设x本身是指针和左值,而不仅仅是某个表达式? 我知道很多人会说“标准不允许它”,但从逻辑的角度看它似乎是合理的。 标准不允许的原因是什么? 毕竟,任何两个指针都具有相同的大小,指针类型只是一个编译时抽象,指示在进行指针运算时应该应用的适当偏移量。

转换void指针

我在旧的C代码中看到了很多以下内容: type_t *x = (type_t *) malloc(…); 从malloc()返回指针的重点是什么,因为它是void * ? 是因为较旧的C编译器不支持void指针而malloc()用于返回char *而不是?

从函数返回指针

我试图从函数返回指针。 但我得到了分段错误。 有人请说出代码有什么问题 #include int *fun(); main() { int *ptr; ptr=fun(); printf(“%d”,*ptr); } int *fun() { int *point; *point=12; return point; }

为什么指针+ 1实际上加4

#include int main(void){ int *ptr,a,b; a = ptr; b = ptr + 1; printf(“the vale of a,b is %x and %x respectively”,a,b); int c,d; c = 0xff; d = c + 1; printf(“the value of cd are %x and %x respectively”,c,d); return 0; } 输出值是 the vale of a,b is 57550c90 and 57550c94 respectively the […]

C指针和数组/’sizeof’运算符

可能重复: char指针和数组的堆栈指针差异 为了说明我的问题: int main(void){ int myary[20]; int *myaryPtr; myaryPtr = myary; sizeof(myary); // Will it return 80? Correct? sizeof(myaryPtr); // Will it return 4? Correct? return 0; } 首先,我的假设是正确的吗? 然后假设我的假设是正确的,详细解释是什么? 我明白我的20个元素数组是80个字节,但是myary这个名字不仅仅是指向数组第一个元素的指针吗? 所以不应该是4吗?

当printf是变量的地址时,为什么要使用void *?

我在printf()看到了(void*)一些用法。 如果我想打印变量的地址,我可以这样做: int a = 19; printf(“%d”, &a); 我想, &a是a只是一个整数的地址,对吧? 我读过的很多文章都是这样的: printf(“%p”, (void*)&a); %p代表什么? (一个指针?) 为什么要使用(void*) ? 我不能用(int)&a代替吗?

malloc的行为(0)

int main() { char *p; p = (char* ) malloc(sizeof(char) * 0); printf(“Hello Enter the data without spaces :\n”); scanf(“%s”,p); printf(“The entered string is %s\n”,p); //puts(p); } 在编译上面的代码并运行它时,程序能够读取字符串,即使我们为指针p分配了一个0字节的内存。 语句p = (char* ) malloc(0)实际发生了什么?

malloc编译错误:类型为“int”的值不能用于初始化int(*)类型的实体

我现在必须尝试过20种方法。 我真的需要帮助,无论我做什么,我都会收到与此类似的错误。 a value of type “int” cannot be used to initialize an entity of type “int (*)[30]” 即这会让我这样的错误 int(*array)[160] = malloc((sizeof *array) * 10); 并做这样的事情 int** Make2DintArray(int arraySizeX, int arraySizeY) { int** theArray; theArray = (int**) malloc(arraySizeX*sizeof(int*)); int i; for (i = 0; i < arraySizeX; i++) { theArray[i] = (int*) malloc(arraySizeY*sizeof(int)); } return […]

Const变量在C中用指针改变

变量i被声明为const,但我仍然可以使用指向它的内存位置的指针来更改该值。 这怎么可能? int main() { const int i = 11; int *ip = &i; *ip=100; printf(“%d\n”,*ip); printf(“%d\n”,i); } 当我编译时,我得到这个警告: test.c: In function ‘main’: test.c:11: warning: initialization discards qualifiers from pointer target type 输出就是这个 100 100

在C中分配矩阵

我想分配一个矩阵。 这是唯一的选择: int** mat = (int**)malloc(rows * sizeof(int*)) for (int index=0;index<row;++index) { mat[index] = (int*)malloc(col * sizeof(int)); }