What is the maximum length of the string element in struct?

Hello,

What is the maximum length of the name?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
#include<stdlib.h>

struct person {
   char *name;
   int age;
};
typedef struct 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.
Last edited on
Thank you,
What about the following code? the opposite name in struct we cannot use it here.

1
2
3
4
5
int main(void) {

   char *name; // 0x10 <error: Cannot access memory at address 0x10>
  scanf("%s",name); 
}
Last edited on
It fails because the pointer isn't actually pointing to anything yet. You need to allocate memory before you can use the C-string pointer.
Last edited on
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.
https://www.guinnessworldrecords.com/world-records/67285-longest-personal-name

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.
Topic archived. No new replies allowed.