2011-01-06 171 views
4

我們可以在C指針初始化疑問

初始化字符指針像這樣

char *c="test";

其中c點的第一個字符(T)。

但是,當我給下面的代碼。它給分段錯誤。

#include<stdio.h> 
#include<stdlib.h> 
main() 
{ 

    int *i=0; 
    printf("%d",*i); 
} 

此外,當我給

#include<stdio.h> 
#include<stdlib.h> 
main() 
{ 
    int *i; 
    i=(int *)malloc(2); 
    *i=0; 
    printf("%d",*i); 
} 

它的工作(給輸出0)。

當我給malloc(0),它的工作(給出輸出0)。

請告訴正在發生的事情

+0

停止鑄造malloc,至少。 – user562374 2011-01-06 11:43:42

回答

5

你的第一個例子是賽格斷層,因爲你試圖去引用您已與行創建一個空指針:

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; 
} 
+0

字符指針的初始化與整數指針不同嗎?因爲我們可以像`char * ptr =「test」那樣初始化它`` – 2011-01-06 06:29:55