【发布时间】:2014-02-22 05:56:38
【问题描述】:
希望创建一个字符串值的动态数组。
在下面的示例代码中,目的是在运行时添加一个新的数组项(realloc)和一个新的字符串(“string 3”)。
我想问题是指针使用不当和/或 realloc 逻辑有问题?
感谢任何帮助。
我得到的实际输出:
Before:
Array[0]: string 1
Array[1]: string 2
After:
Array[0]: string 1
Array[1]: string 2
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **myArray;
main(int argc, char *argv[])
{
int i = 0;
myArray = malloc(2 * sizeof(char*));
int arrayIndexs = sizeof(*myArray) / sizeof(char*);
//Allocate memory for each [x]
for (i = 0; i <= arrayIndexs; i++)
myArray[i] = malloc(254 * sizeof(char*));
//Populate initial values
if(myArray != NULL)
{
strcpy(myArray[0], "string 1");
strcpy(myArray[1], "string 2");
}
//Print out array values
printf("Before: \n");
for (i = 0; i <= arrayIndexs; i++)
printf("Array[%d]: %s\n",i, myArray[i]);
//Expand array to allow one additional item in the array
myArray = (char **)realloc(myArray, sizeof(myArray)*sizeof(char*));
//Allocate memory for the new string item in the array
myArray[arrayIndexs+1] = malloc(254 * sizeof(char*));
//Populate a new value in the array
strcpy(myArray[arrayIndexs+1], "string 3"); //
arrayIndexs = sizeof(*myArray)/sizeof(char*);
//Print out array values
printf("After: \n");
for (i = 0; i <= arrayIndexs; i++)
printf("Array[%d]: %s\n",i, myArray[i]);
}
【问题讨论】: