2014-09-01 70 views
0
#include <stdio.h> 

    int main(void){ 
    char c[8]; 
    *c = "hello"; 
    printf("%s\n",*c); 
    return 0; 
    } 

我最近在學習指針。上面的代碼給了我一個錯誤 - 賦值使指針中的整數沒有轉換[缺省情況下啓用]。 我在SO上讀了幾篇關於這個錯誤的文章,但無法修復我的代碼。 我聲明c爲8個字符的任何數組,c具有第一個元素的地址。所以如果我做* c =「hello」,它將在一個字節中存儲一個字符,並使用「hello」中其他字符所需的字節數。 請有人幫助我確定問題並幫助我解決問題。 mark在字符數組賦值中存儲字符串使得指針中的整數無指針

回答

1

我聲明c爲8個字符的任何數組,c具有第一個元素的地址。 - 是的

所以如果我做* c =「hello」,它會在一個字節中存儲一個字符,並使用「hello」中其他字符所需的字節數。 - 號碼「hello」的值(指向某個靜態字符串「hello」的指針)將被分配給* c(1字節)。 「hello」的值是指向字符串的指針,而不是字符串本身。

您需要使用strcpy將字符數組複製到另一個字符數組。

const char* hellostring = "hello"; 
char c[8]; 

*c = hellostring; //Cannot assign pointer to char 
c[0] = hellostring; // Same as above 
strcpy(c, hellostring); // OK 
+0

所以是char * hellostring是從字符* hellostring不同? – user3551094 2014-09-01 18:52:56

1
#include <stdio.h> 

    int main(void){ 
    char c[8];//creating an array of char 
    /* 
    *c stores the address of index 0 i.e. c[0]. 
    Now, the next statement (*c = "hello";) 
    is trying to assign a string to a char. 
    actually if you'll read *c as "value at c"(with index 0), 
    it will be more clearer to you. 
    to store "hello" to c, simply declare the char c[8] to char *c[8]; 
    i.e. you have to make array of pointers 
    */ 
    *c = "hello"; 
    printf("%s\n",*c); 
    return 0; 
} 

希望對大家有所幫助.. :)

+0

謝謝。所以如果我說* c =「你好」,那麼這意味着我試圖給一個字符分配5個字符。對?指針很難理解。 :( – user3551094 2014-09-01 18:50:51

+0

是的......好吧,如果你試圖理解邏輯,數據是如何存儲的,以及如何獲取數據,那麼你很容易理解它,它並不那麼困難。如果它似乎幫助你.. – Manisha 2014-09-04 08:17:28