【发布时间】:2011-07-27 03:27:25
【问题描述】:
谁能给我解释一下为什么在初始化一个char数组时,如果数组大小留空,像这样
char str1[] = "Hello";
程序会出现段错误,但如果是这样指定的
char str1[10] = "Hello";
效果很好。
这是完整的程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char concat_string(char str[], char str2[], char destination[], unsigned int bufferSize);
int main(int argc, char *argv[])
{
unsigned int bufferSize = 64;
// Both str1 and str2 must be defined
// or else the program will seg fault.
char str1[] = "Hello ";
char str2[] = "World";
char concatenatedString[bufferSize];
concat_string(str1,str2,concatenatedString,bufferSize);
printf("The concatenated string is: \n%s\n", concatenatedString);
return 0;
}
char concat_string(char str[], char str2[], char destination[], unsigned int bufferSize)
{
char buffer[bufferSize];
strncat(str, str2, bufferSize);
strncpy(buffer,str, bufferSize);
strncpy(destination,buffer,bufferSize);
return *destination;
}
【问题讨论】:
标签: c arrays char segmentation-fault