用C整数指针数组初始化 [英] Initializing array of integer pointer in C

查看:203
本文介绍了用C整数指针数组初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对三分球的C.用法我已经把这个例子code以下很容易理解它的一些混乱/问题。请注意这些codeS的差异。如果你有一些问题了解,请有反馈。

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;
}

他们为什么不一样呢?

Why aren't they same?

    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,其中,民; Z ++){而不是为(INT Z = 0; z,其中5; Z ++){静态

任何答案是非常AP preciated。

Any answer is highly appreciated.

先谢谢了。

推荐答案

当你说: 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整数指针数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆