动态分配结构指针数组

时间:2015-04-17 19:36:35

标签: c arrays pointers

我正在尝试使用

为结构(City)指定一个指针数组
City **ptrArray = (City **)calloc(numberOfLines, sizeof(City*));

char tempArray[100];
char* temp = tempArray;
int slength;

for (int i = 0; i < numberOfLines; i++)
    { //Allocates enough memory for array of length of string
        fscanf(fPtr, "%99[^:] %*c", tempArray);
        slength = strlen(temp);
        ptrArray[i] = (City*)malloc(sizeof(int)+(sizeof(char)*slength));
        strcpy(ptrArray[i]->cityName, temp);
        //fscanf(fPtr, "%d", ptrArray[i]->temperature);
    }

这是我将文件中的数据读入数组的地方。调试器(visual studio)只显示ptrArray中的一个单元格,看起来数据丢失了 numberOfLines是指定的int值。 tempArray是从文件读取的字符串的临时保留位置。 temp是指向tempArray的指针。

奖金问题:for循环底部的注释掉的行每次都会破坏代码,我不知道原因。

编辑:我添加了初始化temp和tempArray的代码。 此外,它是对malloc的一个奇怪的调用,因为赋值指定为字符串分配足够的内存和int而不是字符串的最大值。这是我的结构

typedef struct{
    int temperature;
    char cityName[100];
}City;

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

用于动态分配cityName。

typedef struct{
    int temperature;
    char *cityName;// pointer to char
}City;

City **ptrArray = calloc(numberOfLines, sizeof(City*));
if ( ptrArray == NULL) {
    printf ( "calloc failed\n");
    exit(1);
}

char tempArray[100];
int slength;

for (int i = 0; i < numberOfLines; i++)
{
    if ( ( fscanf(fPtr, "%99[^:] %*c", tempArray)) != 1) {
        //handle problem - break or return or exit.
    }
    slength = strlen(tempArray);
    ptrArray[i] = malloc( sizeof(City));// memory for structure
    if ( ptrArray[i] == NULL) {
        printf ( "malloc failed\n");
        exit ( 1);
    }
    ptrArray[i]->cityName = malloc( 1 + slength));// memory for cityName + 1 for '\0'
    if ( ptrArray[i]->cityName == NULL) {
        printf ( "malloc failed\n");
        exit (1);
    }
    strcpy(ptrArray[i]->cityName, tempArray);
    if ( ( fscanf(fPtr, "%d", &ptrArray[i]->temperature)) != 1) {
        //handle problem break or return or exit
    }
}

分配的内存也应该在不再需要时释放。 numberOfLinesptrArray在此函数外可能有不同的名称,而是使用相应的名称。

for ( i = 0; i < numberOfLines; i++) {
    free ( ptrArray[i]->cityName);
    free ( ptrArray[i]);
}
free ( ptrArray);
相关问题