无法在C中正确使用struct指针

0 c arrays struct pointers

我是C的初学者,目前正努力在函数中使用结构体.即使我给我的函数指向我的结构的指针并使用它来改变它们的值似乎我的函数无法改变指针本身的值

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

typedef struct Vector
{
    int n;
    double *entry;
}Vector; 

//defining the struct vector with n for its length and entry as a pointer which will become an array for its values
Vector *newVector(int n)
{
    int i = 0;
    Vector *X = NULL;
    assert(n > 0);
    X = malloc(sizeof(Vector));
    assert(X != NULL);
    X->n = n;
    X->entry = malloc(n+1*sizeof(double));
    assert(X->entry != NULL);
    X->entry[0] = 0;
    for (i=1; i<n+1; ++i) {
        scanf("%lf",&X->entry[i]);
    }
    return X;
}

//making  a new vector struct from the size given and returning its pointer (the array is made so it goes from 1-n instead of 0-(n-1)
void delVector(Vector *X)
{
    assert(X != NULL);
    assert(X->entry != NULL);
    free(X->entry);
    free(X);
    X = NULL;
}

int getVectorLength (Vector *X)
{
    assert(X != NULL);
    return X->n;
}

void setVectorLength(Vector *X, int k)
{
    assert(X != NULL);
    assert(k>0);
    delVector(X);
    printf("so far.\n");
    X = newVector(k);
} //deleting the vector and then replacing it with the new sized vector

double getVectorEntry (Vector *X, int h)
{
    return X->entry[h];
}

void setVectorEntry (Vector *X, int h)
{
    printf("Value %d.\n",h);
    scanf("%lf",&X->entry[h]);
}

main()
{
    Vector *h = NULL;
    h = newVector(3);
    printf("%f\n",h->entry[1]);
    printf("%f\n",getVectorEntry(h,1));
    setVectorEntry(h,1);
    printf("%f\n",getVectorEntry(h,1));
    printf("%d\n",getVectorLength(h));
    setVectorLength(h,6);
    printf("%f\n",getVectorEntry(h,6));
    setVectorEntry(h,6);
    printf("so far.\n");
    printf("%f\n",getVectorEntry(h,6));
}
Run Code Online (Sandbox Code Playgroud)

一旦到达delVector,运行代码就会崩溃.如果我要评论delVector它会崩溃,X = newVector(k);原因我也找不到(它启动函数newVector,但在我输入之前崩溃).那导致错误的原因是什么?非常感谢提前!

小智 6

我们只关注setVectorLength函数

void setVectorLength(Vector *X, int k)
{
    assert(X != NULL);
    assert(k>0);
    delVector(X);
    printf("so far.\n");
    X = newVector(k);
}
Run Code Online (Sandbox Code Playgroud)

这里,Vector*X是仅存在于此函数中的局部变量.它指向内存中的某个位置,但使用它您无法修改原始指针.所以有两种方法可以解决它.1.您不删除并重新创建矢量.而是做这样的事情

void setVectorLength(Vector *X, int k)
{
    X->entry = realloc(X->entry, k*sizeof(double)); // frees X->entry and allocates it to a new heap array
    X->k = k;
}
Run Code Online (Sandbox Code Playgroud)

2.使用指针指针.请注意,这将更慢并且是不必要的.寻找1解决方案.

void setVectorLength(Vector **X, int k)
{
    assert(*X != NULL);
    assert(k>0);
    delVector(*X);
    printf("so far.\n");
    *X = newVector(k);
}
Run Code Online (Sandbox Code Playgroud)

变量Vector**X指向原始变量,因此您可以对其进行修改.