I have recently read a code but I have a doubt in code
toTs *now = try();
now->index = 30;
Where toTs is a struct and try() is a function with return type toTs*
*now being a pointer can keep address of label try() but as try() not being a structure variable now can't access it like struct and can never access it like now->index=30.
After compiling it shows segmentation fault.
I just want to ask is above code legitimate or not.
#include <stdio.h>
#include <unistd.h>
typedef struct toT {
int index;
} toTs;
toTs lst[3];
toTs *try() {
int i;
for (i = 0; i < 3; i++) {
toTs *current = &lst[i];
printf("%d\n", current->index);
if (current->index == 3) {
printf("test work");
return current;
}
}
}
int main() {
int i;
for (i = 0; i < 3; i++) {
lst[i].index = i;
}
for (i = 0; i < 3; i++) {
printf("test %d\n", lst[i].index);
}
toTs *now = try();
now->index = 30;
printf("current %d\n", now->index);
printf("current %d\n", lst[2].index);
}
now is a struct pointer that can point to struct variable but try() is not a struct variable nor array of data structure its a function
toTs&try()?tryis not a keyword/reserved-word in C, so no conflict there. You need to allocate memory fornowinsidetry()or before callingtry().try()function code.