c - 函数的二维字符数组的输出参数

标签 c compiler-errors segmentation-fault

我希望您能为我正在为作业编写的程序的这种方法提供一些输入和二维数组方面的帮助。编程语言是 C 我得到了一些输入参数:

FILE * ifp = input file pointer, opened up in main, opened a txt file with a format of 3 strings per line

char ** firstTokens, middleTokens = 2 dimensional char arrays, I want them to hold the first two strings minus expected punctuation at the end of each string (such as commas and periods). Planned to be an output parameter.

char * lastLetter = The first letter of whatever string is in the last column per line in the txt file. Planned to be an output parameter.

int numberOfLines = number of lines I'm expecting to read from the text file

这是对我的主函数中的方法的调用:

readLine(ifp, firstTokens, middleTokens, lastLetter, numberOfLines);

我认为我的问题是正确获取 firstTokensmiddleTokens,因为我在编辑时总是遇到编译器错误和段错误。非常感谢对错误的一些帮助/澄清。

void readLine(FILE * ifp, char ** firstTokens, char ** middleTokens, char* lastLetter, int numberOfLines)
{
    char* tempFirst;
    char* tempMiddle;
    char* tempLast;
    char delim[4];
    delim[0] = '.';
    delim[1] = '\0';
    delim[2] = '\n';
    delim[3] = ',';
    int i;

    for(i = 0; i < numberOfLines; i++)
    {
        fscanf(ifp, "%s %s %s", tempFirst, tempMiddle, tempLast);
        *firstTokens[i] = strtok(tempFirst, delim);
        *middleTokens[i] = strtok(tempMiddle, delim);
        lastLetter[i] = tempLast[0];
    }
}

最佳答案

您需要为 tempFirsttempMiddletempLast 分配存储空间。 fscanf 写入这些指针,假设您已经为它们提供了足够的内存。

#define MAX_NAME_LEN (20) /* change this as required */
...
char tempFirst[MAX_NAME_LEN];
char tempMiddle[MAX_NAME_LEN];
char tempLast[MAX_NAME_LEN];
...
fscanf(ifp, "%s %s %s", tempFirst, tempMiddle, tempLast);

关于c - 函数的二维字符数组的输出参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13360211/

相关文章:

仅限 Eclipse 外部的 C++ 段错误

c - 当我接受矩阵的第一个值时出现段错误

python - 与 PyOpenCL 的结构对齐

c - 我编码不正确吗?

c - ncurses库编译错误

python - 错误-使用Keras的多分类神经网络

c# - 编译错误 : 'x' conflicts with the declaration of 'y.x' ?

c - C中具有多个警报的多个线程

c - 指针对齐和别名

c++ - 带有 list<..> 的结构在 2 dim 中。删除时的动态数组段错误