2016-11-16 70 views
1

我有一個字符數組,我想設置爲1個變量。我將如何去做這件事。例如,我將有以下代碼:如何將一個字符數組連接成1個變量?

char list[5] = {'B','O','B','B','Y'}; 

我怎麼會擁有它,這樣我可以將其設置爲可變擁有它,這樣:

char *name = "BOBBY" 

從列表拉動值顯示以上。

+2

可能的重複[轉換字符數組到字符串使用C](http:// stackoverflow .com/questions/14344130/convert-char-array-to-string-use-c) –

+1

'char * name = strndup(list,sizeof(list));' – chqrlie

回答

2

除其他答案,對於符合POSIX 1-2008的系統,比如linux和OS/X,有一個更簡單的解決方案:

char *name = strndup(list, sizeof(list)); 
0
char* temp = malloc(sizeof(char) * 6); // 6 because 5 + 1 for null terminator 
for(int i = 0; i < 5; ++i) 
    temp[i] = list[i]; 
temp[5] = '\0'; 

你可以做到這一點,因爲你的陣列是不是空終止我不使用strcpy這一點。

1

由於字符串不是空終止,你不能假設像strcpy功能會成功 - 你需要做的事情在O(n)的那份每個字符一個接一個:

char *str = NULL; 
int len_orig = sizeof(list); 
int i; 

str = malloc(len_orig+1); 
if(!str) 
{ 
    perror("malloc"); 
    exit(EXIT_FAILURE); 
} 
for(i = 0; i < len_orig; i++) 
{ 
    str[i] = list[i]; 
} 
str[len_orig]=0; 

// use str... 

free(str); 
相關問題