Home > Enterprise >  Using pointers when they are elements of a structure array in C
Using pointers when they are elements of a structure array in C

Time:01-05

I want to check if the string SET_NAME is the name of an existing set, and if so, SET1 will point to the address of that set.

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
typedef unsigned char set[16];

int main(){

    char set_name[5] = {'0'};
    char *set1;
    int i;

    set_name[0] = 'S';
    set_name[1] = 'E';
    set_name[2] = 'T';
    set_name[3] = 'B';

    set SETA = {'0'};
    set SETB = {'0'};
    set SETC = {'0'};
    set SETD = {'0'};
    
    struct{
        char *name;
        set *myset;
    }sets[]={
    {"SETA", &SETA}, 
    {"SETB", &SETB},
    {"SETC", &SETC},
    {"SETD", &SETD}
    };  
    
    for(i=0; i < 4;i  ){
        if(strcmp(set_name, sets[i].name)==0){
            set1 = sets[i].myset;
            printf("the set is found!\n%s\n", set_name);
        }
    }
    return 0;
}

This code does not work, probably due to incorrect use of elements in the structure. The compiler writes to me like this: assignment from incompatible pointer type [-Wincompatible-pointer-types] set1 = sets[i].myset; and also- warning: initializer element is not computable at load time [-Wpedantic] {"SETD", &SETD}, for each element in the array. I'm trying to fix and don't understand where my error is.

CodePudding user response:

  1. Never hide arrays or pointers behind typedefs
  2. Your string set_name is too short. It has to be 5 characters long to accommodate null terminating character as well
  3. set_name[0] = {'S'}; makes no sense. If you want to assign a char to the particular element of the array do not use brackets.
  4. set SETA = {'0'}; it will initialize SETA with character '0' as a first element and zeroes the rest.
  5. &SETA has the wrong type (pointer to array of 16 chars, not pointer to char)

After some amendments:

#define SETLENGTH 16

int main(){

    char set_name[] = "SETB";
    char *set1;
    int i;

    char SETA[SETLENGTH] = "";
    char SETB[SETLENGTH] = "";    
    char SETC[SETLENGTH] = "";    
    char SETD[SETLENGTH] = "";    

    struct{
        char *name;
        char *myset;
    }sets[]={
    {"SETA", SETA}, 
    {"SETB", SETB},
    {"SETC", SETC},
    {"SETD", SETD}
    };  
    
    for(i=0; i < 4;i  ){
        if(strcmp(set_name, sets[i].name)==0){
            set1 = sets[i].myset;
            printf("the set is found!\n%s\n", set_name);
        }
    }
    return 0;
}
  • Related