2017-04-18 68 views
0

我是C语言的新手。我需要连接char数组和char。在Java中,我们可以使用'+'操作,但在C中是不允许的。 Strcat和strcpy也不适合我。我怎样才能做到这一点?我的代码如下连接字符数组和char

void myFunc(char prefix[], struct Tree *root) { 
    char tempPrefix[30]; 
    strcpy(tempPrefix, prefix); 
    char label = root->label; 
    //I want to concat tempPrefix and label 

我的问题从concatenate char array in C因为它Concat的字符数组与另一个不同,但矿是一个字符数组使用char

+2

C [concatenate char array可能重复](http://stackoverflow.com/questions/2218290/concatenate-char-array-in-c) –

+1

增加了一个解释我的是如何不同于以前的问题 –

+0

欢迎到堆栈溢出!请说明迄今为止的研究/调试工作。请先阅读[问]页面。 –

回答

1

而是很简单。主要关心的是tempPrefix应该有足够的空间用于前缀+原始字符。由于C字符串必须以空字符结尾,因此您的函数不应复制超过28个字符的前缀。它是30(缓冲区大小)-1(根标签字符)-1(终止空字符)。幸运的是标准库有strncpy

size_t const buffer_size = sizeof tempPrefix; // Only because tempPrefix is declared an array of characters in scope. 
strncpy(tempPrefix, prefix, buffer_size - 3); 
tempPrefix[buffer_size - 2] = root->label; 
tempPrefix[buffer_size - 1] = '\0'; 

这也是值得的不是硬编码在函数调用的缓冲区大小,从而使您可以增加其大小以最小的变化。


如果你的缓冲区不是一个确切的配合,需要一些更多的legwork。该方法与以前几乎完全相同,但需要致电strchr才能完成图片。

size_t const buffer_size = sizeof tempPrefix; // Only because tempPrefix is declared an array of characters in scope. 
strncpy(tempPrefix, prefix, buffer_size - 3); 
tempPrefix[buffer_size - 2] = tempPrefix[buffer_size - 1] = '\0'; 
*strchr(tempPrefix, '\0') = root->label; 

我们再次复制不超过28个字符。但是显式地用NUL字节填充结尾。现在,由于strncpy在NUL字节填充到count的缓冲区中,以防被复制的字符串更短,实际上复制前缀后的所有内容现在为\0。这就是为什么我马上尊重strchr的结果,保证指出一个有效的字符。第一个可用空间是确切的。

+0

我没有得到预期的输出。我可以看到附加字符在我的tempPrefix字符数组的第28个位置,但是当我打印它时,它不在那里。我们不应该将数组连接到数组中当前文本的下一个位置,而应该连接到数组的末尾。 –

+0

@GeorgeKlimas - 我的小错误。 'strncpy'副本*最多*个数字符,包括。这意味着对它的呼叫需要进行调整。查看我的编辑细节。 – StoryTeller

+0

我仍然没有在char数组中追加字符。调试显示角色正被追加到28位置。 –

0

strXXX()系列函数大多操作(除搜索相关的),所以你将无法直接使用库函数。

您可以找到现有空终止符的位置,将其替换为要连接的char值并在其后添加空终止符。但是,您需要确保您有足够的空间让源保留级联的字符串

像这样(未测试)

#define SIZ 30 


//function 
char tempPrefix[SIZ] = {0};  //initialize 
strcpy(tempPrefix, prefix); //copy the string 
char label = root->label;  //take the char value 

if (strlen(tempPrefix) < (SIZ -1)) //Check: Do we have room left? 
{ 
    int res = strchr(tempPrefix, '\0'); // find the current null 
    tempPrefix[res] = label;    //replace with the value 
    tempPrefix[res + 1] = '\0';   //add a null to next index 
} 
+0

我没有在这里得到输出。我可以看到'res'正在变成负值。这是问题吗? –