[英]how to access string member of struct that is dynamically allocated with double pointer
我可以访问具有整数类型成员的双指针结构部分,但是无法访问字符串类型的成员
尝试打印注释掉的部分时出现分段错误,所以我注释掉了。
谢谢。
#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
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++;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.