Pregunta

I've been hammering myself on to this homework for a while now. And I can't seem to find what's wrong with it.

My question is why do I keep getting segmentation fault errors everytime I execute this program.

/* Description: A program that takes an input array argument with type double values and displays a table of those inputs and their absolute values.
*/

...

int main() /* Main Function */
{
    /* Variables */

    int size=5,n;
    double value[n];
    double table;

    /* Instructions and Input */

    for(n=0;n<size;n++){
            printf("\nPlease enter value #%d:\n",n);
            if(n=size-1){printf("\nPlease enter the last value.\n");}
            scanf("%lf",&value[n]);
    }

    /* Recalling the Function and Output */

    printf("\nValue\t|Value|\n"); /* Table Header */
    table=abs_table(value[n],size); /*Absolute Value Table */

    return 0;
}

double abs_table(double value, int size) /* Absolute Value Function */
{
    int i,j; /* Counter Variables */
    double v;

    for(j=1;j<=size;j++){ /* For the Number of rows */
            for(i=0;i<=size;i++){ /* For the number of columns */
                            v = abs(value); // For the absolute values */
                            printf("\n%g\t%g\n",value,v);
                    }
    printf("\n"); /* To make sure the rows display on their own line */
    }

    return;
}
¿Fue útil?

Solución

there are several errors in your code:

Error1: in main() you declare double value[n]; I believe what you want is double value[size];

Error2: in main() statement if(n=size-1) should be changed to if(n==size-1)

Error3: in main() you call function table=abs_table(value[n],size); it should be table=abs_table(value,size);

Error4: you define function double abs_table(double value, int size){...} it should be double abs_table(double value[], int size){...}

Error5: inside function abs_table I actually don't know what you are trying to display here. One spot is that variable i should run from 0 to size-1, another spot is that you should return something

Otros consejos

Many errors are in your program:

  1. Array cannot be initialized with variable length n: double value[n];.
  2. One additional = is missing in if(n=size-1).
  3. Even if you initialized array correctly with length n (point 1) then scanf("%lf",&value[n]); will write to a memory location beyond the length of the value array.
  4. abs is coded for integer but not double: v = abs(value);.
  5. ...possibly some more errors but the list is already quite long.

In main you declare int n without initialising it and subsequently double value[n]. Therefore n has an undefined value and thus value is of undefined size. I think you meant to declare double value[size], which you did initialize.

Also, abs_table is supposed to return a double but you're returning void.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top