2014-03-06 17 views
1

我開始學習C中的指針。如何修復C中的指針錯誤?

如何解決我在函數x()中的錯誤?

這是錯誤:

Error: a value of type "char" cannot be assigned to an entity of type "char *". 

這是完整的源:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <stdarg.h> 

void x(char **d, char s[]) { 
    d = s[0]; // here i have the problem 
} 

void main() { 
    char *p = NULL; 
    x(&p, "abc"); 
} 
+3

這個問題不斷變化,以微妙的方式,使評論不再相當準確了。 –

+0

您最近編輯的程序沒有錯誤,只是一個警告。如果你打算使用'p',它確實有一個bug。 – Brian

+0

現在更改示例源代碼最多4個編輯。這是一個移動的目標! – EkoostikMartin

回答

3

在功能x()傳遞d其爲char **(指針的字符串指針)和char s[](數組char,類似地傳遞給指向的指針)。

所以在線路:

d = s[0]; 

s[0]char,而char **d是一個指針的指針char。這些是不同的,編譯器說你不能從一個指派給另一個。

但是,你的編譯器真的警告你如下?

Error: a value of type "char" cannot be assigned to an entity of type "char *"

鑑於代碼示例,它應該在末尾說char **

認爲你正在嘗試做什麼x do是將作爲第二個參數傳遞的字符串的地址複製到第一個指針中。這將是:

void x(char **d, char *s) 
{ 
    *d = s; 
} 

這使得p於呼叫指向常量字符串xyz但不復制的內容。

如果當時的想法是複製字符串的內容:

void x(char **d, char *s) 
{ 
    *d = strdup(s); 
} 

,並確保你還記得free()返回值main(),以及在頂部加入#include <string.h>

+0

你明白我的意思。我shuld實施strcpy()。但我知道strcpy()函數,通過enother來複制一個。 – user2986392

+1

只有在您試圖複製字符串的*內容*而不僅僅是指向它的指針時才需要'strcpy'。如果(比如說)稍後修改了字符串,則會有顯着差異。哪一個是正確的取決於你想要做什麼。在您瞭解指針時,瞭解其中的差異是關鍵。在任何情況下,如果您要使用庫函數複製字符串的*內容*,只需使用'strdup()'。 – abligh

-2

更合適的方式是使用strcpy

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <stdarg.h> 

void x(char **d) { 
    *d = malloc(4 * sizeof(char));   
    strcpy(*d, "abc"); 
} 

int main() { 
    char *p; 
    x(&p); 
    printf("%s", p); 
    free(p); 
    return 0; 
} 

輸出:ABC

+0

-1 for hardcoding'5',ah,and BTW,sizeof(char)== 1 –

+0

@KarolyHorvath:這是因爲你只分配給實際字符,但是一個字符串還包含一個特殊的終止符字符,你需要空間以及。 – Brian

+0

耶穌。讓我換個方式:-1來硬編碼一個常量。 –

-1

這裏是你可以做什麼,所以它會在兩個版本編譯。

第1版。

void x(char **d, char s[]) { 
    d = (char**)s[0]; 
} 

或第2版。

void x(char **d, char *s) { 
    *d = s; 
} 

希望這有助於。

+0

你當然是對的。修正了,抱歉 - 工作習慣:/ – imkort

+0

沒問題;-) –