【问题标题】:C: segmentation fault when running function from another fileC:从另一个文件运行函数时出现分段错误
【发布时间】:2015-10-19 02:01:47
【问题描述】:

当我运行这段代码时,它会一直运行,直到我到达我的 main 函数中的 printf 语句,这就是我得到分段错误错误的时候。所以它会像“输入你想要的数字”3“输入数组中的数字”一样运行 1 2 3 array[0] = 1 array[1] = 2 array[2] = 3 分段错误。你们能告诉我为什么我会收到这个错误以及如何解决它吗?谢谢你

//pathfinder.c    
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Vector.h"

int main()
{
    Vector *V;
    VectorRead(V);
    printf("%d", V->item[0]);
    return 0;
}

//Vector.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef struct{
int *item;
int size;
} Vector;

void VectorRead(Vector *V) ;

void VectorRead(Vector *V)
{
    int N;
    printf("Enter how many numbers you want?\n");
    scanf("%d", &N);
    V = (Vector *)malloc(sizeof(Vector *) * N);
    V->size = N;
    V->item = (int *)malloc(sizeof(int *) * V->size);
    printf("Enter the numbers that you want in your array\n");
    int i = 0;
    while(i < V->size && scanf("%d", &(V->item[i++])) == 1);
    int j;
    for(j = 0; j< V->size; j++){
            printf("array[%d]=%d\n", j, V->item[j]);
    }
}

【问题讨论】:

  • C 是按值传递。更改函数中的参数不会影响调用者中的参数。
  • ...但是如果将参数的地址作为指针传递,则可以更改此指针所针对的值。
  • @peterh: ...或者你可以做理智的事情和return一个指针。
  • @EOF 顺便说一句,C 的美妙之处在于它的肮脏。 :-) 是的,C 主要是按值传递,但数组是按地址传递的。 C中没有规则,没有例外:-)嗯,它是在BCPL之后的下一步命名的,但实际上它缩写为我_C_haos :-)
  • 您在两次 malloc 调用中都分配了错误的字节数。这可以通过使用模式p = malloc( N * sizeof *p ); 来避免

标签: c


【解决方案1】:

此错误与您的代码位于不同文件中无关。

当您调用VectorRead() 时,您传递的是一个指针值。在该函数中,您将 local V 设置为对 malloc() 的调用的返回值。本地V 无法返回给调用者。

您需要做一些事情来将新分配的V 值返回给调用者。更改您的函数以返回 Vector *(而不是将其作为参数)将是一个好方法。

【讨论】:

    【解决方案2】:

    当调用VectorRead() 时,您的本地VectorV 不会被修改。尝试在您的函数中接受 Vector **

    void VectorRead(Vector **V)
    

    并相应地修改函数。

    或者,由于您的函数没有返回值,并且正如 @EOF 在 cmets 中指出的那样,最好采用参数,而只需返回 Vector *

    Vector *VectorRead(void)
    

    【讨论】:

    • 为什么每个人都想让人们使用多重间接?只是return该死的指针!
    • 这是一个选项。但是,在某些情况下,它可能更安全,而不是简单地返回,或者如果需要不同的返回值等。
    • 鉴于 OP 的函数是 void,将其更改为返回 Vector * 似乎并不难。
    • Vector *VectorRead(void);会更好,因为那是原型。
    猜你喜欢
    • 1970-01-01
    • 2013-11-30
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多