C - 逐行读取文本文件到指针数组,得到 BAD_ACCESS

标签 c xcode pointers exc-bad-access

我用 Xcode 编写。我的代码应该将文本文件逐行读取到指针数组 *ar[] 中。我使用了一个简单的循环,通过 getc() 将每个字符读取到 c,并将 c 读取到 *ar[i]。如果 c!= '\n' *ar[i] 递增。否则,*ar[i] 和 i 都会递增。为了便于牵引,我在每一步之后都添加了“printf”。 问题:程序将第一行读取到 *ar[0],但是一旦 i 递增到 1,我就会得到 EXC_BAD_ACCESS(代码=2,地址=0x10000000000)。 MAC 的 VIM 给出 Bus error:10。在增量中发生了一些我无法理解的事情。

#include <stdio.h>

#define MAXLINE 10



int main()
{

    FILE *file;
    int i = 0;
    char *ar[MAXLINE];
    char c;


    file = fopen("/Users/ykeshet/Desktop/lab/alice30.txt", "read");

    while ((i < MAXLINE) && ((*ar[i]) = c = getc(file)) != EOF){
        if (c != '\n'){
            printf("%c",c);
            (*ar[i])++;
            }
        else{
            printf("%c",c);
            (*ar[i])++;
            i++;
            }
        }

    printf("\n");

}

This is the output I get (first line)

That's the variable's state in the debugger:

最佳答案

说明这里的错误:

char *ar[MAXLINE];

这声明了一个指向 charMAXLINE 指针数组。这些指针保持未初始化状态,它们不指向有效位置,取消引用它们是未定义的行为。实际上,它们可能指向一些或多或少的“随机”位置,并且您的操作系统将阻止您写入您的进程不允许的某些地址。

while ((i < MAXLINE) && ((*ar[i]) = c = getc(file)) != EOF){
//                        ^ undefined behavior

    if (c != '\n'){
        printf("%c",c);
        (*ar[i])++;

为什么要增加 a[i] 指向的字符?您可能想在 a[i] 应该指向的不存在的“字符串”中前进一个。 that 您需要另一个指针,否则您的程序会“忘记”您的字符串从哪里开始。


遵循基于您的原始结构的工作程序,但使用 fgets 和静态缓冲区。如果您需要动态分配内存,或者如果您出于某种原因坚持逐个字符地读取,这留作练习。

#include <stdio.h>
#define MAXLINE 10
#define LINEBUFSIZE 1024

int main()
{
    FILE *file;
    int i = 0;
    char ar[MAXLINE][LINEBUFSIZE];

    file = fopen("/Users/ykeshet/Desktop/lab/alice30.txt", "r");
    if (!file) return 1;

    while ((i < MAXLINE)
    {
         // read in next "line" by giving a pointer to the
         // first element as buffer for fgets():
         if (!fgets(&(arr[i++][0]), LINEBUFSIZE, file)) break; 
    }
    fclose(file);
    // i now holds the number of lines actually read.

    return 0;
}

关于C - 逐行读取文本文件到指针数组,得到 BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44612602/

相关文章:

c - C 中的 scanf string 和 printf 不能按预期工作

C 附加两个字符串

ios - 我试图在我的 ViewController 上放置多个 UICollectionView,但只有一个 UICollectionView 在模拟上运行

c++ - 改变指针变量的内容

c++ - 字符串类中指针和整数的比较 - C++

c - 传递指向函数的指针

c - 将结构体转换为 int 类型

c - GTK2:不推荐使用 g_thread_init

objective-c - 当键盘出现在 iOS 中时,将 UIView 上移

ios - 父 View 中的 Swift 容器控件