-1

I have a little problem passing a pointer inside a void. This void show only the firts position of the array of struct. When the loop go to second position i get "segmentation fault".I tried to show the array inside the main with the same loop and it works.What's the problem?

typedef struct starr{
    char string[100];
    int occ;
} starr;

int main(){
    int n;
    starr *array_str;
    //insert n and array_str
    array_str=(starr *)malloc(sizeof(starr)*n);
    view(&array_str,n);
}

void view(starr *array_str, n){
    int i;
    for(i=0;i<n;i++){
        printf("String %s",array_str[i]->string);
    }
}
Morten Jensen
  • 5,818
  • 3
  • 43
  • 55
Jilz
  • 31
  • 5

1 Answers1

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

typedef struct starr {
    char string[100];
    int occ;
} starr;

void view(starr *array_str, size_t n);

int main() {
    size_t n;
    // initialize n
    starr *array_str;
    array_str = (starr *)calloc(n, sizeof(starr));
    // do stuff with array_str
    view(array_str, n);

    free(array_str); // go! be free!
}

void view(starr *array_str, size_t n) {
    size_t i;
    for(i = 0; i < n; i++){
        printf("String %s", array_str[i].string);
    }
}

1: view accepts a starr *, and array_str is already that type so there is no need to reference it with &.

2: since array_str is a starr *, an index of it (e.g. array_str[i]) is a starr so use the . notation instead of the -> notation.

3: calloc will clear the bytes when declaring memory so that they will be initialized to NULL bytes and you'll avoid printing a string that may cause buffer overflow, if you don't give them proper values first for whatever reason.

4: n should be type size_t to be consistent with its meaning, which is the number of indices in an array.

5: don't forget to free(array_str); since you initialized it using malloc / calloc.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • Thanks for support. I fixed it deleting the '&'. Of course its only a part of the code. It's just an example of the problem because i have no internet now to post all the complete code. I wrote alla of that with my phone. Thank you again – Jilz May 04 '15 at 16:54