你的第一个例子是赛格断层,因为你试图去引用您已与行创建一个空指针:
int *i=0;
你不能去 - 引用一个指向任何东西并指望好事发生的指针。 =)
第二个代码段的工作原理是因为您已经使用malloc实际为内存指定了您可以取消引用的malloc。我认为你可能得到的值不是零,这取决于与malloc分配的地址相邻的内存。我这样说是因为通常int是4个字节,而你只分配了2个。当取消引用int指针时,它应该根据指向的4个字节返回值作为int。在你的情况下,前2个字节是你从malloc收到的内容,相邻的2个字节是任何可能是任何东西的东西,不管它是什么,都将被视为是一个整型。你可能会得到这样的奇怪行为,你应该使用你想要使用/指向的类型所需的内存大小。
(即int *i = (int *) malloc(sizeof(int));
)
一旦你在内存中的指针指向是正确的尺寸,然后你可以设置值,例如:
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char *argv[])
{
int *i = (int *)malloc(sizeof(int));
*i = 25;
printf("i = %d\n",*i);
*i = 12;
printf("i = %d\n",*i);
return 0;
}
编辑基于评论:
指针指向内存,而不是值。当初始化char *ptr="test";
你并没有使用“测试”的价值,你分配在编译器把它放置在你的进程数据段是只读的“测试”的内存地址。它试图修改字符串“测试”,你的程序可能会seg-fault。你需要了解的一个char *是它指向字符串中的单个(即第一个)字符。当您取消引用char *时,您只会看到1个字符和一个字符。 C使用以空字符结尾的字符串,并且注意在调用printf时不要取消引用ptr,而是将指针本身传递给它,并指向第一个字符。这是如何显示取决于传递给printf的格式。当printf的是通过了“%c”格式,它将在打印单个字符PTR点,如果传递的格式“%P”,它会打印ptr指向的地址。要获取整个字符串,您需要传递'%s'作为格式。什么这使得printf的做的是开始你传入的指针,直至达到零读取每个连续的字节。以下是一些演示这些代码的代码。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[])
{
// Initialize to data segement/read only string
char *ptr = "test";
printf("ptr points at = %p\n", ptr); // Prints the address ptr points to
printf("ptr dereferenced = %c\n", *ptr); // Prints the value at address ptr
printf("ptr value = %s\n", ptr); // Prints the string of chars pointed to by ptr
// Uncomment this to see bad behavior!
// ptr[1] = 'E'; // SEG FAULT -> Attempting to modify read-only memory
printf("--------------------\n");
// Use memory you have allocated explicitly and can modify
ptr = malloc(10);
strncpy(ptr, "foo", 10);
printf("ptr now points at = %p\n", ptr); // Prints the address ptr points to
printf("ptr dereferenced = %c\n", *ptr); // Prints the value at address ptr
printf("ptr value = %s\n", ptr); // Prints the string of chars pointed to by ptr
ptr[1] = 'F'; // Change the second char in string to F
printf("ptr value (mod) = %s\n", ptr);
return 0;
}
停止铸造malloc,至少。 – user562374 2011-01-06 11:43:42