#include <stdio.h>
#include<stdlib.h>
struct person {
char *name;
int age;
};
typedefstruct person Person;
int main(void) {
// This code works fine.
Person P;
scanf("%s",P.name);
printf("%s",P.name); //What is the maximum length of the name?
}
you didn't allocate any memory for it.
when you do, its the maximum chunk of ram that the OS is willing to give to you, which could be anywhere from a few MB to 10s of GB.
if this is C++, person is already a type. It looks more like C, which I forget ... may need the typedef there.
BTW, I am not a fan. I much prefer just making a flat array to allocating memory unless the max sensible size simply is not known and it can range from 0 to millions of letters from object to object.
that looks like
1 2 3 4 5 6 7
#define max_string_size 1000 //if in C?
...
struct s
{
char name[max_string_size];
...etc
}
there are few reasons to make name sized to fit, and plenty not to.
The longest known personal name is 747 characters long, so if you declare the max string size as being 1000, as jonnin did, you've got more than enough excess space.
You can create the C string on the heap or the stack with that size. Personally I'd do it on the stack so you don't have to do manual memory management. Plus the C string library has functions to deal with most if not all needs for string management.
With a predetermined size hard-coded can help reduce manual memory management issues if putting the string on the heap is still desired. Allocate a set size from the app start, no reallocation needed should the name size change.