更改位于结构中的双指针。

huangapple go评论49阅读模式
英文:

Changing a double pointer which is in a struct

问题

I'm trying to change the x value in this code but I'm getting segmentation fault.

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int **x;
} Type;

int main() {
    int a = 1;
    Type *type = malloc(sizeof(Type));
    type->x[0] = &a;
    return 0;
}
英文:

I'm trying to change the x value in this code but I'm getting segmentation fault.

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

typedef struct
{
    int **x;
} Type;

int main() {
    int a = 1;
    Type *type = malloc(sizeof(Type));
    type-&gt;x[0] = &amp;a;
    return 0;
}

答案1

得分: 0

if you want an array of pointers to ints

int main() {
    int a = 1;
    Type *type = malloc(sizeof(Type));
    type->x = malloc(sizeof(int*) * 10)) ;// say we need 10
    type->x[0] = &a;
    return 0;
}
英文:

if you want an array of pointers to ints

int main() {
    int a = 1;
    Type *type = malloc(sizeof(Type));
    type-&gt;x = malloc(sizeof(int*) * 10)) ;// say we need 10
    type-&gt;x[0] = &amp;a;
    return 0;
}

huangapple
  • 本文由 发表于 2023年2月6日 03:38:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355001.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定