通过使用一系列指针从结构中访问字符串

Accessing string from a structure, by using a series of pointers

typedef struct {
    char numeVolum[50]; ////this is what interests us!!!
    short int anPublicare; 
    unsigned char stare; 
    int idPersoana; 
} TVolum; 

typedef struct { 
    char numeAutor[50];  
    char codTara[2];  
    int nrVolume; 
    TVolum* volume;  /////this is what interests us!!!
} TAutor; 

这两个结构都是动态分配的! listaAutori[0] 是指向 TAutor 结构的指针数组! (可以断定 listaAutori 是 TAutor** 类型)

fgets(listaAutori[0] -> numeAutor, 50, input); 
fgets(listaAutori[0] -> codTara, 3, input); 
fgets(listaAutori[0] -> volume[0].numeVolum, 53, input); 

前两个 fget 读取正常。 但是第三个没有给我任何输出。

printf("\nNUme primul volum al lui Agatha: %s\n", listaAutori[0] -> volume[0].numeVolum);

换句话说,我有两个结构,A和B。 在 B 里面,我有一个字符串。 (指向字符的指针)

结构A中有一个指针pB。 还有一个指向 A 的指针数组。

像这样:

包含 pA 元素的指针数组 -> 结构 A -> pB -> 结构 B -> 我的字符串。

我正在尝试从文件中读取一行,并将该字符串存储在 numeVolum[50] 字符串中。我可以访问 TVolum 的唯一方法是使用指向 TAutor 的指针。

我不知道什么不起作用,printf 没有给我任何输出。 它应该打印了一些东西。 (我从中读取数据的文件包含每一行的信息)

Autor* alocaAutor(int nrVolume) 
{ 
    TAutor* autor = (TAutor*)calloc(1, sizeof(TAutor));  
    autor -> volume = (TVolum*)calloc(nrVolume, sizeof(TVolum)); 
    autor -> nrVolume = nrVolume; 
    return autor; 
} 

TAutor** alocaAutori(int nrAutori, int* nrVolumeAutor) 
{
    int i;
    TAutor** vectorAutori = (TAutor**)calloc(nrAutori, sizeof(TAutor*));  
    for(i = 0; i < nrAutori; i++) {
        vectorAutori[i] = alocaAutor(nrVolumeAutor[i]); 
    } 
    return vectorAutori; 
} 

输入文件示例:

2 
1 
1
Agatha Christie
UK
Ultimul caz al lui Hercule Poirot

我 100% 肯定它会读取最后一行之前的所有内容。 然后,当我尝试从 TVolume 读取字符串中的最后一行时,它根本不起作用。

char *fgets(char *str, int n, FILE *stream)

在读取 n-1 个字符时停止 (source)。因为第二个fgetsn的值是3,它只读取输入文件中的UK。其后的换行符尚未读取。然后由 third fgets 读取,它立即遇到换行符,不会进一步读取。因此,输入文件中的最后一行未被读取。

您编辑的代码(在您的评论中)有效,因为 fscanf 读取该换行符并停在该字符处,让 fgets 读取最后一行。