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:
- Never hide arrays or pointers behind
typedef
s - Your string
set_name
is too short. It has to be 5 characters long to accommodate null terminating character as well 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.set SETA = {'0'};
it will initializeSETA
with character'0'
as a first element and zeroes the rest.&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;
}