Home > front end >  Setting array of pointers
Setting array of pointers

Time:09-21

i'm doing a small exercise to load an array of pointers (double pointer) to a struct. I have the following definition in the header file:

#include <stdio.h>

#define LEN (5)

typedef struct sample_s {
    int num;
    char *name;
}sample_t;

typedef struct new_sample_s {
    char *string;
    sample_t **sample_arr;
}new_sample_t;

sample_t table[LEN] = {
    {0, "eel"},
    {1, "salmon"}, 
    {2, "cod"},
    {3, "tuna"},
    {4, "catfish"}
};

and using the definitions int this .c file:

#include "test.h"

void print_new_sample_array(sample_t **sample_arr) {
    int len = sizeof(table)/sizeof(new_sample_t);
    for(int i = 0; i < len; i  ){
        printf("The array element is: %s\n", sample_arr[i]->name);
    }
}

int main() {

    new_sample_t new_sample;
    new_sample.sample_arr = table;

    print_new_sample_array(new_sample.sample_arr);

    return 0;
}

I have two questions:

First I'm not sure how to correctly load the table to the new_sample.sample_arr Error message here:

test.c: In function ‘main’:
test.c:13:27: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
     new_sample.sample_arr = table;
                           ^

Second, I'm not sure how I can refer to the properties of each element in the sample_arr. For example, when I do the following, the program errored out:

for(int i = 0; i < LEN; i  ){
    printf("This is the elem in the array: %s", new_sample[i]->name);
}

I'm trying to learn more about the double pointer concept and why I did it wrong. I would really appreciate the answer keeps the sample_arr as double pointer

Thank you!

CodePudding user response:

In this assignment statement

new_sample.sample_arr = table;

the right operand (after implicit conversion of the array to pointer to its first element) has the type sample_t * while the left operand has the type sample_t ** due to the declaration of the data member

sample_t **sample_arr;

There is no implicit conversion from the type sample_t * to the type sample_t **. So the compiler issued a message.

You should declare the data member like

sample_t *sample_arr;

and correspondingly the function declaration will look like

void print_new_sample_array(sample_t *sample_arr);

And within the function the call of printf will look like

printf("The array element is: %s\n", sample_arr[i].name);
  • Related