繁体   English   中英

我不断出现细分错误

[英]I keep getting segmentation fault

我需要将三个数组vetor1vetor2vetor3到一个名为conjunto的大数组中,但是在运行代码时,我总是遇到分段错误。

我使用函数iniciaiza创建一个50位置的数组,并用0填充该数组。然后,在read函数中,我将读取一个数组(大多数情况下,数组的大小为3),然后在add函数中,我需要将三个数组复制到我使用malloc创建的数组。 最后,我需要打印三个数组,并打印所有三个数组的副本。

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

int *conjunto;
int *vetor1, *vetor2, *vetor3, n1, n2, n3;
int tam = 50;

void inicializa (int **tconj, int tam)
{
    int i;
    *tconj = (int *) malloc (tam * sizeof(int));
    for (i = 0; i < tam; i++)
    {
        tconj[i] = 0;
    }
}

void read (int **vec, int *n)
{
    int i;
    printf("size of array: ");
    scanf ("%d", n);
    printf("array: \n");
    *vec = (int *) malloc (*n * sizeof(int));
    for (i = 0; i < *n; i++)
    {
        scanf ("%d", &(*vec)[i]);
    }
}

void add (int *conjunto, int *vetor1, int *vetor2, int *vetor3, int n1, int n2, int n3)
{
    int i, j, k, w;
    int fim1 = (n1 + n2);
    int fim2 = (n1 + n2 + n3);
    for (i = 0; i < n1; i++)
    {
        conjunto[i] = vetor1[i];
    }
    for (j = n1; j < fim1; j++)
    {
        conjunto[j] = vetor2[j];
    }
    for (k = fim1; k < fim2; k++)
    {
        conjunto[k] = vetor3[k];
    }
}

void print_array (int *vec, int n)
{
    int i;
    printf("array: ");
    for (i = 0; i < n; i++)
    {
        printf("%d ", vec[i]);
    }
    printf("\n");
}

int main()
{
    inicializa (&conjunto, tam);

    read (&vetor1, &n1);
    read (&vetor2, &n2);
    read (&vetor3, &n3);

    print_array (vetor1, n1);
    print_array (vetor2, n2);
    print_array (vetor3, n3);

    add (conjunto, vetor1, vetor2, vetor3, n1, n2, n3);

    print_array (conjunto, tam);

    return 0;
}

您的初始化功能几乎不错,只是缺少一颗小星星:

void inicializa (int **tconj, int tam)
{
    int i;
    *tconj = (int *) malloc (tam * sizeof(int));
    for (i = 0; i < tam; i++)
    {
        (*tconj)[i] = 0;
    }
}

同样,您应在以这种方式读取输入后在主目录中调用它:

tam = n1 + n2 + n3;
inicializa (&conjunto, tam);

在程序结束时,在return之前,您应该添加:

free(conjunto);
free(v1);
free(v2);
free(v3);

编辑:我错过了add()其他两个错误。

void add (int *conjunto, int *vetor1, int *vetor2, int *vetor3, int n1, int n2, int n3)
{
    int i, j, k;
    int fim1 = (n1 + n2);
    int fim2 = (n1 + n2 + n3);
    for (i = 0; i < n1; i++)
    {
        conjunto[i] = vetor1[i];
    }
    for (j = n1; j < fim1; j++)
    {
        conjunto[j] = vetor2[j - n1];
    }
    for (k = fim1; k < fim2; k++)
    {
        conjunto[k] = vetor3[k - fim1];
    }
}

编辑2:如果用户添加有趣的值(例如零或负大小数组),也将不起作用,我将这些控件留给您。

在你的函数add你正在阅读vetor2[j]; vetor3[k]; 但是jk可能超出vetor

for (i = 0; i < tam; i++)
{
    // This is not doing what you think it is.
    // You are setting some memory locations at and after tconj to zero,
    //  which is not the array you just allocated.  
    // The pointer to array that you just allocated is now 0
    tconj[i] = 0; // pretty sure you mean *tconf[i] 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM