只是尝试将N
字符串扫描到数组并动态分配它们
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 3
#define MAX_STR_LEN 20
void main(void) {
char* str_arr[N] = { ' ' };
char temp_str[MAX_STR_LEN] = { ' ' };
for (size_t i = 0; i < N; i++)
{
//scan string
fgets(temp_str, MAX_STR_LEN, stdin);
strtok(temp_str, "n");
// next line of code triggers breakpoint at second iteration
*(str_arr + i) = (char*)calloc((strlen(temp_str) + 1), sizeof(char));
if (!(str_arr + i))
{
printf("Could not allocate memoryn");
return 1;
}
//copy temporary string to dedicated string
strcpy_s(*(str_arr + i), sizeof(temp_str), temp_str);
}
printf("n");
system("PAUSE");
}
一些观察:
- 您没有分配
sizeof(temp_str)
.您已分配strlen(temp_str)+1
.因此,第一个strcpy_s
将导致缓冲区溢出,这就是为什么在循环的第二次迭代中出现问题的原因。 - 语句
if (!(str_arr +i))
不检查指针 刚刚分配 *(str_arr + i)
与str_arr[i]
相同,后者更容易 对于阅读代码的人- 在第
char* str_arr[N] = { ' ' };
行中,你声明了一个指针数组,但你用一个字符常量 (