I faced to a problem about to make "Sets" with struct on C.
I had initialized two struct pointers(S1, S2). At first time to initialize the pointers and print there address with %p has work, but after to access the functions with S2, It doesn't work. I checked pointer after access the function. Address of S2 became a NULL. I don't know how can I fix this problem..
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define defaultSize 5
typedef enum {FALSE, TRUE} Boolean;
typedef struct {
int nElements;
int arraySize;
char **element;
} strset_t;
strset_t *createSet()
{
strset_t *s;
if((s = (strset_t*)malloc(sizeof(strset_t))) != NULL){
s->element = (char **)malloc(sizeof(char *) * defaultSize);
s->nElements = 0;
s->arraySize = defaultSize;
}
return s;
}
void deleteSet(strset_t *s)
{
free(s->element);
free(s);
}
int cardinality(strset_t *s)
{
return s->nElements;
}
int isElement(char *x, strset_t *a)
{
for(int i = 0; i < a->nElements; i++)
if(strcmp(x, a->element[i]) == 0)
return i;
return -1;
}
Boolean addElement(char *x, strset_t *a)
{
if(a->nElements == a->arraySize){
a->arraySize *= 2;
a = realloc(a, a->arraySize);
puts("== extended ==");
}
if(a == NULL){
puts("=== NULL ===");
return FALSE;
}
a->element[a->nElements] = (char *)malloc(strlen(x) + 1);
strcpy(a->element[a->nElements], x);
a->nElements++; //deep copy를 사용하여 값 전달
return TRUE;
}
Boolean removeElement(char *x, strset_t *a)
{
int idx = isElement(x, a);
if(idx == -1){
puts("=== Not found ===");
return FALSE;
}
for(int i = idx; i < a->nElements - 1; i++){
free(a->element[i]);
a->element[i] = a->element[i + 1];
}
free(a->element[a->nElements - 1]);
a->nElements--;
}
int main()
{
strset_t *S1, *S2;
S1 = createSet();
S2 = createSet();
Boolean run = TRUE;
char target, selection;
char buff[100];
while(run){
printf("%p %p\n", S1, S2);
fflush(stdin);
switch (getchar()) {
case '1':
printf("Target(1, 2)) : ");
scanf("%d", &target);
fflush(stdin);
printf("Element : ");
if(target == 1)
addElement(gets(buff), S1);
else if(target == 2)
addElement(gets(buff), S2);
break;
case '2':
printf("Target(1, 2)) : ");
scanf("%d", &target);
fflush(stdin);
printf("Element : ");
if(target == 1)
removeElement(gets(buff), S1);
else if(target == 2)
removeElement(gets(buff), S2);
break;
case 'X':
run = FALSE;
break;
default:
puts("== Invalid menu ==");
getchar();
break;
}
printf("\n");
}
deleteSet(S1);
deleteSet(S2);
system("pause");
return 0;
}
fgets
and strip the trailing'\0'
2)"%p"
wants a cast:(void *)S1
scanf("%d", &target);
- it requires anint
yettarget
is achar
.