C语言动态内存疑问
我定义了一个动态二维数组代码
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *ptr1 = (char *)malloc(6*sizeof(char));
ptr1 = "abcabc";
char **ptr2 = (char **)malloc(6*sizeof(char *));
ptr2 = ptr1;
printf("%s\n",ptr2);
free(ptr1);
free(ptr2);
return 0;
}
结果成功了,但后面两句不知道为什么出现.
abcabc
free(): invalid pointer
zsh: abort (core dumped)./a.out
2 个错误
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
//char *ptr1 = (char *)malloc(6*sizeof(char));
char *ptr1 = (char *)malloc(7*sizeof(char));
//ptr1 = "abcabc";
strcpy(ptr1, "abcabc");
char **ptr2 = (char **)malloc(6*sizeof(char *));
ptr2 = ptr1;
printf("%s\n",ptr2);
free(ptr1);
free(ptr2);
return 0;
}
页:
[1]