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
CodePudding user response:
You need to always return a valid toTs*
from try()
for the code to work.
#include <stdio.h>
#include <unistd.h>
typedef struct toT {
int index;
} toTs;
toTs lst[4];
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;
}
}
return &lst[3]; // return a spare structure.
}
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);
for (i = 0; i < 4; i ) {
printf("Final %d\n", lst[i].index);
}
}
You're confusing function pointers with plain pointers in C. Function pointers go deeper : https://en.wikipedia.org/wiki/Function_pointer
CodePudding user response:
This code is not particularly healthy.
Given the way lst
is initialized, when you call try()
it will reach the end of that function without a return statement.
The C Standard says that if you use the return value of a function, without actually returning a value, that's undefined behavior.