【问题标题】:process returned -1073741819 <0xC0000005>进程返回 -1073741819 <0xC0000005>
【发布时间】:2019-06-20 14:43:00
【问题描述】:

我是编码和学习 c 语言的初学者,这是我的第一步。 当我使用字符串函数时,程序返回一个值而不显示输出。使用 minGW 作为编译器

我尝试添加 string.h 标头文件夹 细绳 从下面跟随代码

''''
#include <stdio.h>
#include <conio.h>

int main()
{
    /*
    int strlen(string);
    */
    char name = { 's','i','l','a','m','\0' };

    int length;

    length = strlen(name);
    printf("the length of %s is %d\n", name, length);

    getch();
    return 0;
}
'''

代码到此结束

希望打印字符名称的长度,但它崩溃了 和构建日志一样 “进程以 -1073741819 状态终止” 在构建消息中 警告:传递 'strlen' 的参数 1 使指针从整数而不进行强制转换 [-Wint-conversion]| 注意:预期为 'const char *' 但参数的类型为 'char'|

感谢您的关注

【问题讨论】:

  • 您没有收到其他警告吗?认真对待警告。
  • 你使用的是哪个编译器?
  • 您需要将name 定义为char name[] 而不是char nameprintf 中的 %s 需要字符串而不是字符。另外,您需要#include &lt;string.h&gt; 转为strlen()
  • 您正在使用getch();,MS 不赞成使用 _getch();,因此您可能习惯于看到您忽略的警告消息。您必须确定为什么会有警告消息。理想情况下应该没有。
  • 永远不要忽视警告!除了“警告:传递 'strlen' 的参数 1 使指针从整数而不进行强制转换”之外,您还应该看到“警告:标量初始化程序中的多余元素”只要有警告,就不要尝试运行程序。跨度>

标签: c windows


【解决方案1】:

您将name 声明为char,但您将其视为数组。要将name 声明为char 数组,请使用:

char name[] = { 's','i','l','a','m','\0' };

另外由于你引用了函数strlen(),所以你必须添加头文件:

#include <string.h>

【讨论】:

    【解决方案2】:

    享受:

    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
        // single char can't store that string
        // so we have to declare an array of chars
        char name[] = {'s', 'i', 'l', 'a', 'm', '\0'}; 
        // also we can use string literal syntax:
        // char name[] = "silam";
        int length = strlen(name);
        printf("the length of %s is %d\n", name, length);
        getc(stdin);
        // i don't have <conio.h> so i call 'getc' instead of 'getch'
        return 0;
    }
    

    【讨论】:

    • strlen() 返回size_t,顺便说一句。
    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    相关资源
    最近更新 更多