2011-04-18 165 views
5
char *tempMonth; 

char month[4]; 
month[0]='j'; 
month[1]='a'; 
month[2]='n'; 
month[3]='\0'; 

如何將月份指定給tempMonth?謝謝指定一個字符串值指針

以及如何最終打印出來?

感謝

回答

1
tempmonth = malloc (strlen (month) + 1); // allocate space 
strcpy (tempMonth, month);    //copy array of chars 

記住:

include <string.h> 
+0

有一個緩衝區溢出等待發生。始終使用'strncpy',並確保tempMonth指向正確分配的內存。 – 2011-04-18 03:58:41

+0

我沒有降低你的評分,但我認爲你的分配應該是'strlen(month)+ 1'。 'sizeof(tempmonth)'是_pointer._ – paxdiablo 2011-04-18 03:59:15

+0

的大小哦。你是對的。對不起 – Freaktor 2011-04-18 04:00:14

10

在C中,month == &month[0](大多數情況下),並且這些等於char *或字符指針。

所以,你可以這樣做:

tempMonth=month; 

這將指向未分配的指針tempMonth指向在其他5條線路的職位分配的字面字節。

要使一個字符串,它也是這樣更簡單:

char month[]="jan"; 

或者(雖然你是不允許修改在這一個字符):

char *month="jan"; 

的編譯器會自動分配month[]右側文字的長度,並使用適當的以NULL結尾的C字符串,並且month將指向文字。

要打印:

printf("That string by golly is: %s\n", tempMonth); 

您不妨審查C strings and C string literals

+0

只是一些建議:在第一行中將'='改爲'==',並明確說明'month ==&month [0]'_mostly._使用sizeof或某些其他語言功能時不會這樣。 – paxdiablo 2011-04-18 04:09:08

+0

是的,同意...... – 2011-04-18 04:11:51

+0

@paxdiablo:是的,很好的編輯。謝謝。 – 2011-04-18 04:20:55

2
tempMonth = month 

當你給一個指針賦值時 - 它是一個指針,而不是一個字符串。通過如上分配,您不會奇蹟般地擁有相同字符串的兩個副本,您將有兩個指針(monthtempMonth)指向相同的字符串。

如果你想要的是一個副本 - 你需要分配內存(使用malloc),然後實際複製值(使用strcpy如果它是一個空終止字符串,memcpy或循環其他)。

0

你可以這樣做:

char *months[] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug","Sep","Oct", "Nov", "Dec"}; 

並訪問

printf("%s\n", months[0]); 
2

如果你只想指針的一個拷貝,可以使用:

tempmonth = month; 

但這意味着兩者都指向相同的基礎數據 - 更改一個並影響博日。

如果你想獨立的字符串,有一個很好的機會,你的系統將具有strdup,在這種情況下,你可以使用:

tempmonth = strdup (month); 
// Check that tempmonth != NULL. 

如果您的實施strdupget one

char *strdup (const char *s) { 
    char *d = malloc (strlen (s) + 1); // Allocate memory 
    if (d != NULL) strcpy (d,s);   // Copy string if okay 
    return d;       // Return new memory 
} 

爲了以格式化的方式打印字符串,請查看printf家族,儘管對於像這樣的簡單字符串轉換爲標準輸出,puts可能已經足夠好了(可能更有效率)。

1
#include "string.h" // or #include <cstring> if you're using C++ 

char *tempMonth; 
tempMonth = malloc(strlen(month) + 1); 
strcpy(tempMonth, month); 
printf("%s", tempMonth); 
+0

有人會說,如果你使用'printf'或'malloc',那麼你不可能使用C++ - 你被困在煉獄中等待完全轉換:-) – paxdiablo 2011-04-18 04:11:02

+0

是真的。儘管如此,你仍然可以包含C庫。你永遠不會知道 ;) – 2011-04-18 04:34:17