|
60鱼币
- #include <stdio.h>
- #include <string.h>
- #define LEN 40
- void build_index_url (const char *domain, char *index_url);
- int main(void)
- {
- char domain[LEN] = {0}, index_url[LEN] = {0};
- printf ("Enter a URL: ");
- scanf ("%s", domain);
- build_index_url(domain, index_url);
- puts(index_url);
- return 0;
- }
- void build_index_url (const char *domain, char *index_url)
- {
- char *http = "http://www.";
- char *html = "/index.html";
- /* strcat(http, domain);
- strcat(http, html);
- strcpy(index_url, http);
- */
- strcpy(index_url, strcat(strcat(http, domain), html));
- }
复制代码
gdb看,第一个 strcat 一调用就出错了,请问问题在哪啊?
问题出在`char *http = "http://www.";`这行代码上。你声明的`http`是一个指向字符串常量的指针,它指向的是只读内存区域。当你尝试使用`strcat`函数拼接字符串时,这将导致未定义的行为。
要解决这个问题,你可以将`http`声明为一个字符数组,并初始化为包含所需字符串的空间大小。例如,可以修改代码如下:
- char http[LEN] = "http://www.";
复制代码
此外,你还需要注意`domain`和`index_url`的声明方式。它们应该是字符数组而不是字符变量。修改代码如下:
- char domain[LEN] = {0}, index_url[LEN] = {0};
复制代码
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
|
最佳答案
查看完整内容
问题出在`char *http = "http://www.";`这行代码上。你声明的`http`是一个指向字符串常量的指针,它指向的是只读内存区域。当你尝试使用`strcat`函数拼接字符串时,这将导致未定义的行为。
要解决这个问题,你可以将`http`声明为一个字符数组,并初始化为包含所需字符串的空间大小。例如,可以修改代码如下:
此外,你还需要注意`domain`和`index_url`的声明方式。它们应该是字符数组而不是字符变量。修改代码如下:
...
|