c - C 中 char 数组的错误

标签 c

我想用 C 语言将以下 html 打印到控制台。但是,我的代码中有一个错误让我很困惑,我不知道怎么会发生这种情况?错误是它再次打印最后一个字符数组。

示例输出:

<html>
    <body>
        <p>Hey There!</p>
        <p>You can search for things on the internet at:
            <ul>
            <li> <a href="http://www.google.com">Google</a></li>
            <li> <a href="http://www.bing.com">Bing</a></li>
            </ul>
        </p>
    </body>
    </html>

My output:
<html>
    <body>
        <p>Hey There!</p>
        <p>You can search for things on the internet at:
            <ul>
            <li> <a href="http://www.google.com">Google</a></li>
            following line is incorrect. It prints the above line again.
            <li> <a href="http://www.bing.com" href="http://www.google.com">Bing</a></li> 
            </ul>
        </p>
    </body>
    </html>

我的代码:

#include <stdio.h>
#include <stdint.h>
#include <string.h>
void open_tag(char tag[], char attribute[]){
char str1[100];
char str2[100];
char str3[100];
//The bug happens here.The attribute[] is incorrect.
strcpy (str1,tag);
strncat (str1, attribute, 100);
strcpy (str2,"<");
strcpy (str3,">");
strncat (str2, str1, 100);
strncat (str2, str3, 50);
printf ("%s",str2);
}
void close_tag(char tag[]){
char str1[20];
char str2[20];
char str3[20];
strcpy (str1,tag);
strcpy (str2,"</");
strcpy (str3,">");
strncat (str2, str1, 6);
strncat (str2, str3, 6);
printf ("%s",str2);
}

int main(int argc, char *argv[])
{
open_tag("html", "");
printf("\n");
open_tag("body", "");
printf("\n");
open_tag("p", "");
printf("Hey There!");
close_tag("p");
printf("\n");
open_tag("p", "");
printf("You can search for things on the internet at:");
printf("\n");
open_tag("ul", "");
printf("\n");
open_tag("li", "");
char arr2[] = {' ','h','r','e','f','=','\"','h','t','t','p',':','/','/','w','w','w','.','g','o','o','g','l','e','.','c','o','m','\"'};
open_tag("a", arr2);
printf("Google");
close_tag("a");
close_tag("li");
printf("\n");
open_tag("li", "");
char arr1[] = {' ','h','r','e','f','=','\"','h','t','t','p',':','/','/','w','w','w','.','b','i','n','g','.','c','o','m',' ','\"'};  
open_tag("a", arr1);
printf("Bing");
close_tag("a");
close_tag("li");
printf("\n");
close_tag("ul");
printf("\n");
close_tag("p");
printf("\n");
close_tag("body");
printf("\n");
close_tag("html");
printf("\n");
return 0;
}

最佳答案

当您创建并传递attribute时,它不是 null 终止的。然后强制它复制 100 个字符(使用 strcat ),然后在其末尾附加字符( <> )

我建议你在 arr1 上放置一个终结符字符和arr2在传递字符串之前(通过添加 '\0' 字符)。

那就不要使用strncat(..., 100) ,只需使用简单的 strcat() .

关于c - C 中 char 数组的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14805969/

相关文章:

c - 如何在 gcc 中为复数启用 SSE3 addsubps 自动矢量化?

c - 多处理器架构中的状态机事件生成

c - 如何使用 MinGW 和 Sublime Text 3 构建 GLUS

c - SDL_FillRect 中的段错误

c - 在C中将字符转换为字符串

c - BSS和数据段默认有哪些数据?

c - 处理部分 : does a declaration add also something to . 文本?如果是,它添加了什么?

android - 使用 NDK 精确的 POSIX 线程计时

c - 隐式声明警告 : What are the built-in functions?

c - 具有子结构的 C 语言结构的 Doxygen XML 输出