小编Rav*_*avi的帖子

在 C 程序中使用 0 而不是 '\0'

为什么我的程序没有进入无限循环。我没有用'\0'while 循环测试字符串结尾,而是使用0. 是否'\0'0同在C 2

如果是,那么如果0在字符串的中间,那么printf应该在那里结束打印字符串。例如 printf("%s", "hello how0 are you") 应该打印 'hello how'

int main( )
{
    char s[ ] = "No two viruses work similarly" ;
    int i = 0 ;
    while ( s[i] != 0 )
    {
        printf ( "%c", s[i]) ;
        i++ ;
    }
}
Run Code Online (Sandbox Code Playgroud)

c printf c-strings char while-loop

4
推荐指数
10
解决办法
279
查看次数

C 错误需要“char **”,但参数的类型为“char (*)[10]”

我正在尝试实现我的版本strcat。但是,我收到以下警告,并且我的代码在运行时崩溃。我正在传递&pmain函数p中的变量进行永久更改main

\n

警告:

\n
note: expected \xe2\x80\x98char **\xe2\x80\x99 but argument is of type \xe2\x80\x98char (*)[10]\xe2\x80\x99\n
Run Code Online (Sandbox Code Playgroud)\n

代码:

\n
#include <string.h>\n#include <stdio.h>\n\nvoid mystrcat(char **p, char *q)\n{\n    while (**p != '\\0')\n    {\n        *p++;\n    }\n\n    while (*q != '\\0')\n    {\n        **p = *q;\n        (*p)++;\n        q++;\n    }\n    *p = '\\0';\n}\n\nint main()\n{\n    char p[10] = "ravi";\n    char q[12] = "ra";\n\n    mystrcat(&p, q);\n    printf("%s", p);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

c pointers c-strings strcat function-definition

3
推荐指数
1
解决办法
1万
查看次数

在 C 中返回本地变量地址与本地字符串地址

下面的程序没有运行,因为我们正在返回本地 int 值。

#include<stdio.h>

int *fun1()
{
    int i = 10;
    return &i;       // local i hence will not get printed in main
}

main()
{
    int *x = fun1();

    printf("%d", *x);
}
Run Code Online (Sandbox Code Playgroud)

然而,在下面的程序运行的同时,即使我们正在返回本地字符串基地址。为什么本地 char* 的概念在这里不适用?

char *fun()
{
    char *p = "ram";
    return p;             //char* is local, even though in main it gets printed. why?
}

int main()
{
    char *x = fun();
    printf("%s", x);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c scope string-literals storage-duration

0
推荐指数
1
解决办法
78
查看次数