【发布时间】:2017-06-30 07:17:26
【问题描述】:
我有一个 SmartArray 的结构 typedef,它有一个变量 char **array。我已经尝试调试代码几个小时,并取得了很大进展。但是,我被困在这个特定的错误上。我有一个功能可以打印出所述数组。它将打印两次,然后第三次根本不打印!我有一种感觉,这与我如何将 malloc 添加到数组中有关,因为一个数组打印不正确。对于数组的最后一部分,它打印“Testing Na”。有任何想法吗?我将不胜感激。
这是我怀疑是函数的部分原因,但是,我似乎找不到它://为字符串分配最小空间
printf("approaching malloc\n");
strPtr = malloc( sizeof(char) * (strlen(str) + 1) );
if(strPtr == NULL)
{
return NULL;
}
printf("made it past malloc!\n");
strcpy(strPtr, str);
//if crash probably this code
smarty->array[index] = strPtr;
if(smarty->array[0] == NULL)
{
return NULL;
}
return strPtr;
这是我的测试代码:
typedef struct SmartArray
{
// We will store an array of strings (i.e., an array of char arrays)
char **array;
// Size of array (i.e., number of elements that have been added to the array)
int size;
// Length of the array (i.e., the array's current maximum capacity)
int capacity;
} SmartArray;
int main(void)
{
int i; char buffer[32];
SmartArray *smarty1 = createSmartArray(-1);
printf("Array created\n");
// Print the contents of smarty1.
printf("\n-- SMART ARRAY 1: --\n");
printSmartArray(smarty1);
printf("Made it past print!\n");
put(smarty1,"Hi, my name is ");
put(smarty1, "Hello, my name is");
put(smarty1, "Testing Names");
printf("made it past put!\n");
printf("smart away is now\n");
printSmartArray(smarty1);
printf("end of main!\n");
我觉得这是很明显的事情,我只是忽略了因为我是新手。
这是一张我试图让它在内存中看起来像的图片: click here for memory diagram
更新:我知道为什么它没有打印所有名称,但程序在打印功能后出现段错误。
【问题讨论】:
-
您的代码中没有二维数组。也没有
int **。请注意,int **之类的东西不是二维数组,不能指向一个!它是一个指向指针的指针,它是一种与数组数组完全不同的数据类型并且读取How to Ask 并提供一个minimal reproducible example。 -
@Olaf 我已将其添加到我的代码中。
-
你平时对用户大喊大叫吗?
-
@Ed Heal 不,我只是碰巧为我的调试语句设置了大写锁定。我希望我可以立即删除它们,但几个小时后我仍然无法调试它。
-
printf或put位在情人大小写中如何,但引号中的内容在大写字母中
标签: c dynamic allocation