在一行中将字符串设为null

fud*_*din 5 c for-loop

为了使字符串成为空字符串我写了这个:

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
    char str[15]="fahad uddin";
    strlen(str);
    puts(str);
    for(int i=0;str[i]!='\0';i++)
        strcpy(&str[i],"\0") ;
    puts(str);
    getch();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在此之前,我试过:

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
    char str[15]="fahad uddin";
    strlen(str);
    puts(str);
    for(int i=0;str[i]!='\0';i++,strcpy(&str[i],"\0"))
        ;
    puts(str);
    getch();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在第一个示例中,程序运行正常,而在第二个示例中,它打印字符串的第一个字母(在此示例中为F).为什么是这样?

ken*_*ytm 11

C字符串以空值终止.只要您只使用假设以空字符结尾的字符串的函数,您就可以将第一个字符归零.

str[0] = '\0';
Run Code Online (Sandbox Code Playgroud)


use*_*313 8

memset(str,0,strlen(str)); /* should also work */
memset(str,0,sizeof str); /* initialize the entire content */
Run Code Online (Sandbox Code Playgroud)


Wil*_*l A 5

for(int i=0;str[i]!='\0';i++,strcpy(&str[i],"\0")); - 在strcpy执行之前i ++正在递增 - 所以它将在第一次迭代时获取str [1]的地址 - 跳过str [0] - 因此你将得到第一个字符.

请注意,KennyTM的反应是一种更好的方法 - 但我想你正在学习/尝试.