c - 尝试存储指针数组

标签 c

struct match
{
    char men[64];
    char women[64];
    char menNum[1000];
    char woNum[1000];
};

void printOut();
int matchMaking(struct match* p, struct match* q, int k);
int main(void)
{
    FILE* fin;
    FILE* fout;
    fin = fopen("input.txt", "r");
    fout = fopen("out.txt", "w");
    int matchNum = 0;
    int size;
    int i;
    int j;
    int a;
    struct match* ptrName;
    struct match** ptrNum;
    char* str;
    char temp[800];

    if(fin == NULL)
        printf("Cannot Find File");

    fgets(temp, 800, fin);
    str = (char*)malloc(sizeof(char));
    str = (char*)strtok(temp, " \n");
    size = atoi(str);
    printf("Size = %d\n", size);

    ptrName = (struct match*)malloc(size*sizeof(struct match));
    ptrNum = (struct match**)malloc(size*sizeof(struct match*));

    for(i = 0; i < size; i++)
    {

        fgets(temp, 800, fin);
        str = (char*)strtok(temp, " \n");
        matchNum = atoi(str);
        printf("Match Num = %d\n", matchNum);
        fgets(temp, 800, fin);
        strcpy(ptrName->men, temp);
        printf("Name = %s\n", ptrName->men);
        fgets(temp, 800, fin);
        strcpy(ptrName->women, temp);
        printf("Name = %s\n", ptrName->women);

        for(j = 0; j<matchNum; j++)
        {
            fgets(temp, 800, fin);
            strcpy(ptrNum[j]->menNum, temp);
            printf("Men Num = %d\n", ptrNum[j]->menNum);
        }

调试时我不断收到段错误错误

最佳答案

粗略地说,我想说问题出在这里:

ptrNum = (struct match**)malloc(size*sizeof(struct match*));

您真正想要的是足够的内存来容纳 size 数量的 struct match,而不是 size 数量的指针。然后您想要索引到该空间。

实际上,你应该做类似的事情

struct match* ptrNum = malloc(size*sizeof(struct match));

这将为您提供一个用于 size 个结构体的内存块,并为您提供指向第一个结构体的指针。您可以使用简写的“数组”表示法对此内存进行索引,因此 match[0] 会为您提供“数组”中位置 0 处的结构,并且 match[j] > 为您提供第 j 个位置的记录。

另请注意,match[j] 会返回实际内存,因此您不会想使用指针表示法:

strcpy(ptrNum[j].menNum, temp);

关于c - 尝试存储指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3818243/

相关文章:

c - 将 VP9 编码数据混合到 .webm 时 FPS 不正确

C++ Tweetnacl 散列文件而不将整个文件读入内存

c++ - char* argv[] 在 C/C++ 中如何工作?

c - 使用记事本构建 C 应用程序的自动化工具

c - 需要一些关于简单 C 代码程序的建议

c - 在 C 中,为什么我可以将函数名(不是指针)作为参数传递给函数?

c - 交换 2 个字节的整数

c - 如何从 C 中的函数返回多个值?

c++ - 如何区分客户端是从服务器端使用 TCP 还是 UDP

c - 仅使用一个矩阵在 C 中通过部分主元实现 LU 分解