问题描述
我对 C 中指针的使用有一些困惑/问题.我将示例代码放在下面以便于理解.请注意这些代码的差异.如果您在理解上有任何问题,请反馈.
I have some confusions/problems about the usage of pointers in C. I've put the example code below to understand it easily. Please notice differences of these codes. If you have some problem understanding it, please have a feedback.
这不起作用.
#include <stdio.h>
#include <stdlib.h>
void process() {
int *arr;
arr=(int*)malloc(5*sizeof(int));
arr=(int*){3,1,4,5,2};
for(int z=0;z<5;z++) {
printf("%d ",arr[z]);
}
printf("\n");
}
int main() {
process();
return 0;
}
但这行得通.
#include <stdio.h>
#include <stdlib.h>
void process() {
int *arr;
arr=(int*)malloc(5*sizeof(int));
arr=(int[]){3,1,4,5,2};
for(int z=0;z<5;z++) {
printf("%d ",arr[z]);
}
printf("\n");
}
int main() {
process();
return 0;
}
这也有效.为什么?我这里没有分配内存.
This also works too. Why? I didn't allocate memory here.
#include <stdio.h>
#include <stdlib.h>
void process() {
int *arr;
arr=(int[]){3,1,4,5,2};
for(int z=0;z<5;z++) {
printf("%d ",arr[z]);
}
printf("\n");
}
int main() {
process();
return 0;
}
为什么它们不一样?
arr=(int*){3,1,4,5,2};
arr=(int[]){3,1,4,5,2};
有没有其他方法来初始化整型指针数组,而不是用这种单独的赋值方式?
Is there any other way to initializing array of integer pointer, not using in this individual assigning way?
arr[0]=3;
arr[1]=1;
arr[2]=4;
arr[3]=5;
arr[4]=2;
如何获得指针内存中分配的大小/数量,以便我可以使用类似 for(int z=0;z<NUM;z++) {
而不是 for(int z=0;z 静态的?
How can i get the size/number of allocation in memory of pointer so that i can use something like for(int z=0;z<NUM;z++) {
instead of for(int z=0;z<5;z++) {
statically?
非常感谢任何答案.
提前致谢.
推荐答案
当你说:ptr = {1,2,3,4,5}
,你就制作了 ptr
指向数据段中的内存,其中常量数组 {1,2,3,4,5}
驻留,因此您正在泄漏内存.如果你想初始化你的内存,就在分配之后,写:ptr[0]=1;ptr[1]=2;
依此类推.如果要复制数据,请使用 memcpy.
When you say: ptr = {1,2,3,4,5}
, you make ptr
point to a memory in the data segment, where constant array {1,2,3,4,5}
resides and thus you are leaking memory. If you want to initialize your memory, just after allocation, write: ptr[0]=1; ptr[1]=2;
and so on. If you want to copy data, use memcpy.
这篇关于在 C 中初始化整数指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!