【发布时间】:2016-10-06 03:29:21
【问题描述】:
我正在编写一个程序,它从文件中读取信息,为每一行的结构分配内存,并用信息填充该结构。然后将指向该结构的指针放置在全局数组中。
文件中的每一行(第一行除外)的格式为“Unsigned Char - Char - Unsigned Char - Char[]”。
我的问题是每次我添加一个新结构时,所有其他结构中的 Char[] 都会被覆盖。
假设我有以下文件:
1 10 6 first
2 12 7 second
3 15 6 third
当我使用该文件运行我的程序,然后打印全局数组时,它会给出如下输出:
ID: 1 | FLAGG: 10 | STR_LEN: 6 | MODELL: third
ID: 2 | FLAGG: 12 | STR_LEN: 7 | MODELL: third
ID: 3 | FLAGG: 15 | STR_LEN: 6 | MODELL: third
而不是预期的:
ID: 1 | FLAGG: 10 | STR_LEN: 6 | MODELL: first
ID: 2 | FLAGG: 12 | STR_LEN: 7 | MODELL: second
ID: 3 | FLAGG: 15 | STR_LEN: 6 | MODELL: third
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 256
struct myStruct* globarlArray[MAX_LENGTH]
struct mySTruct{
unsigned char ID;
char FLAGG;
unsigned char str_len;
char* modell;
};
int set_variables(struct myStruct* s, unsigned char new_ID, char new_FLAGG, unsigned char new_str_len, char* new_modell){
s->ID = new_ID;
s->FLAGG = new_FLAGG;
s->str_len = new_str_len;
s->modell = new_modell;
return 0;
}
int main(int argc, char* argv[]){
//Read from file
...
//Initialize structs, add variables to struct, and add struct to global array
unsigned char ID;
int ID_INT;
char FLAGG;
unsigned char str_len;
char modell[253];
char* tempstr;
for (i = 1; i < lines; i++){
tempstr = str[i]; //str[1] is first line of into from file, str[2] is second line,...
Ruter_ID = tempstr[0];
Ruter_ID_INT = Ruter_ID;
FLAGG = tempstr[1];
str_len = tempstr[2];
sprintf(modell, "%s", tempstr+3);
struct myStruct *line = (struct myStruct*)malloc(sizeof(struct myStruct));
set_vars(line, ID, FLAGG, str_len, modell);
globalArray[ID_INT] = line;
}
//print array
for (i = 0; globalArray[i] != NULL; i++){
printf("ID: %d | FLAGG: %d | str_len: %d | Modell: %s",
globalArray[i]->ID, globalArray[i]->FLAGG, globalArray[i]->str_len,
globalArray[i]->modell);
}
//Some more code
...
}
提前致谢!
【问题讨论】:
-
请贴出可以编译的真实代码
-
你只有一个字符缓冲区,
char modell[253];。您的代码使所有s->modell指向同一个缓冲区。 -
指针懂吗?