为什么我为以下代码收到"无效的初始化程序错误"?
#include<stdio.h>
#include<malloc.h>
int main(){
int i = 2;
int j;
for(j = i ; j < 20; j++){
char *p[5] = malloc(20 * sizeof(char));
int len = 0;
p[0] = 'a';
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你有一个指针数组,你只需要指向一个指针:
char *p[5] = malloc(20 * sizeof(char));
Run Code Online (Sandbox Code Playgroud)
请改用:
char *p = malloc(20 * sizeof(char));
Run Code Online (Sandbox Code Playgroud)
如果你真的想要一个指针数组,但只设置它们中的第一个,这应该是你的代码:
char *p[5] = {malloc(20 * sizeof(char))};
Run Code Online (Sandbox Code Playgroud)
(或者甚至更好:char *p[5] = {0}; p[0] = malloc(20 * sizeof(char));)
如果这是你想要的,你必须以不同的方式对字母'a'进行设置 - *(p[0]) = 'a';而是使用.
此外:你不再释放你的记忆.你应该free(p);这样做,否则你的程序可能会消耗越来越多的内存.
对于小程序,这没有问题,因为操作系统在程序关闭后无论如何都会释放内存.
但这是不好的做法,以及许多糟糕软件的原因.
| 归档时间: |
|
| 查看次数: |
187 次 |
| 最近记录: |