Segmentation fault when accessing pointer contents

4

I need to declare a vector of pointers, which will point to types float , and do a simple reading of values.

The program compiles but after entering 4 values I get a Segmentation fault (core dumped) .

Why does this occur because I've reserved 10 spaces and am trying to access them?

#include <stdio.h>

void main(){
float *vet[10];
int i = 0;
    for(i = 0; i < 10; i++){
    puts("Digite um valor:");
    scanf("%f", vet[i]);
    printf("%f", *vet[i]);
    }
}
    
asked by anonymous 22.12.2015 / 12:55

1 answer

5

The solution is simpler than it sounds. From what I understand the use of the pointer is inappropriate in this code. Using the vector is enough to solve the problem.

#include <stdio.h>

int main() {
    float vet[10];
    for (int i = 0; i < 10; i++) {
        printf("\nDigite um valor: ");
        scanf("%f", &vet[i]); //preciso passar o endereço do elemento do vetor
        printf("%f", vet[i]);
    }
    return 0;
}

See running on ideone .

I used to improve some things and make the code more modern and up to standard.

You can change this code to use pointers .

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

int main() {
    float *vet = malloc(sizeof(float) * 10);
    for (int i = 0; i < 10; i++) {
        printf("\nDigite um valor: ");
        scanf("%f", &vet[i]);
        printf("%f", vet[i]);
    }
    return 0;
}

There you do not need the vector. Note that pointers and vectors are concepts that can be reasonably interchangeable under certain circumstances in C . Reading the linked question here gives you to understand why even having allocated with pointer, I was able to use vector index syntax, which is just syntax sugar for a pointer access calculation . You could give the calculation on hand to use the pointer syntax, but it's unnecessary.

The difference is that the first code allocates memory in the stack , and this with pointer allocates in heap .

    
22.12.2015 / 13:10