如何访问使用双指针

时间:2016-03-18 02:13:35

标签: c pointers struct double

我能够访问具有integer类型成员的双指针结构部分,但是我无法访问string类型的成员

在尝试打印出已注释掉的部分时出现分段错误,所以我对此进行了评论。

感谢。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BLOCK 2
#define LINESIZE 1024
#define NLINES 1000
#define NAMESIZE 20


typedef struct{
    char last[NAMESIZE];
    char first[NAMESIZE];
}name;

typedef struct{
    name name;
    int score;
}record;

typedef struct{
    record *data;
    size_t nalloc;
    size_t nused;
}record_list;

int main(void){


record **lines, **p;
char buffer[LINESIZE];
size_t i, j, nalloc, nused;

nalloc = nused = 0;
lines =0;

while(fgets(buffer, LINESIZE, stdin)){
    if(nused == nalloc){
    p = realloc(lines, (nalloc + BLOCK) * sizeof(record*));

    if(p==0){
        fprintf(stderr, "realloc failed\n");
        break;
    }
    lines = p;
    nalloc +=BLOCK;
    }
    lines[nused] = malloc(sizeof(record));

    if(lines[nused] == 0){
        fprintf(stderr, "malloc failed\n");
        break;
    }
    lines[nused++]->score = 50+nused;
    /* strcpy(lines[nused++]->name.first,"hello");
    strcpy(lines[nused++]->name.last,"last"); */

}

for(i = 0; i < nused; i++)
    printf("%d ", lines[i]->score);

for(i = 0; i < nused; i++)
    printf("%s ", lines[i]->name.first);

}

最后一个输出也没有输出任何东西输出? 输出:

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

1 个答案:

答案 0 :(得分:0)

lines[nused++]->score = 50+nused;
/* strcpy(lines[nused++]->name.first,"hello");
strcpy(lines[nused++]->name.last,"last"); */

注释掉的代码行中的问题是nused每行都被错误地递增。 nused(在任何增量之前)是引用已分配缓冲区的最后一个索引。所以nused只应在用于所有数组访问之后递增

lines[nused]->score = 50+nused;
strcpy(lines[nused]->name.first,"hello");
strcpy(lines[nused]->name.last,"last");
nused++;