将字符数组写入 C 中的文件时出现分段错误 [英] Segmentation fault when writing char array to file in C

查看:150
本文介绍了将字符数组写入 C 中的文件时出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行以下代码时,我在 fprintf(outfile, "%s", inputline[j]); 处收到一个 分段错误".>

我无法理解错误的原因是什么.我对 C 比较陌生,有人可以帮我解决这个错误吗?

void test(char *inputline) {FILE *outfile = fopen("results.txt", "w");如果(!输出文件){perror("打开文件时出错:");} 别的 {for (int j = 0; j < 20; ++j) {//我只想将前 20 个字符写入文件,这就是为什么我只有 20 个迭代并添加 [j],是正确的方法吗?fprintf(outfile, "%s", inputline[j]);}}}//函数调用...char inputline[40] = "hello world 123 456";//传递给上面的函数测试(输入线);

解决方案

格式说明符 %s in

fprintf(outfile, "%s", inputline[j]);

期望一个 char * 变量,但您实际上传递的是一个 char (inputline 的 j th 元素数组).

出现分段错误的原因是fprintf 试图访问"传递的字符所指向的内存位置.而且由于它很可能是无效地址,操作系统会抱怨尝试访问分配给您的应用程序的空间之外的内存.

您可以打印到文件 char by char,保持 for 循环并使用 %c 格式

 for(int j=0; j<20; ++j){fprintf(outfile, "%c", inputline[j]);}

或打印整个字符串保持 %s 格式,传递整个数组并摆脱 for 循环:

fprintf(outfile, "%s", inputline);

注意:无论如何,在第一种情况下将写入 20 个字符.在第二种情况下,由于字符串终止符 '\0'.

When I run the following code, I get a "Segmentation fault" at fprintf(outfile, "%s", inputline[j]);.

I am unable to understand what is the cause for the error. I am relatively new to C, can someone please help me resolve the error?

void test(char *inputline) {
    FILE *outfile = fopen("results.txt", "w");   
    if (!outfile) {
        perror("Error while opening file: ");
    } else {
        for (int j = 0; j < 20; ++j) { // I only want to be write the first 20 characters to the file that is why I have the iteration till only 20 and added [j], is that correct way to do it?
            fprintf(outfile, "%s", inputline[j]);
        }
    }
}

//Function call
    ...
    char inputline[40] = "hello world 123 456"; //passed to the function above
    test(inputline);

解决方案

Format specifier %s in

fprintf(outfile, "%s", inputline[j]);

expects a char * variable, but you are actually passing a char (j th element of inputline array).

The reason why a segmentation fault occurs is that fprintf tries to "access" the memory location poited by the passed character. And since it will be very likely an invalid address the OS will complain about the attempt to access the memory outside the space assigned to your application.

You can either print to file char by char, keeping the for-loop and using %c format

 for(int j=0; j<20; ++j)
 {
     fprintf(outfile, "%c", inputline[j]);
 }

or print the whole string keeping the %s format, passing the whole array and getting rid of the for-loop:

fprintf(outfile, "%s", inputline);

Note: in the first case 20 characters will be written, anyway. In the second case "length+1" characters because of the string terminator '\0'.

这篇关于将字符数组写入 C 中的文件时出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆