strlen, help

Please, i would like to understand the following syntax:
char[strlen(buffer)+1] (look at the code for details).

I know what strlen() does,but i do not understand the char[....] syntax.
Why is it using the suqare brackets [] and a data type together? is there a reference to study more on such wierd syntax?

Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct title
{
    char first_name[21];
    char surname[21];
};
int main()
{
    struct title *user;
    char buffer[20]="some name here";
    user.surname=(title *)malloc(sizeof(char[strlen(buffer)+1] ));// <---my problem is here
    strncpy(user->surname,buffer,20);
    cout << user->surname;

}
]

i fixed a terrible mistake that distorted my question. before editing it was:
malloc(char[strlen(buffer)+1] );
Last edited on
You have already allocated memory for that character array so you don't need nor want that malloc() call.

By the way why did you define buffer with a size of 20 instead of 21?

First off, line 10 is wrong on several counts.

To answer your question about the syntax, consider the following:
1
2
3
4
5
6
7
8
  size_t len;
  len = strlen(buffer) + 1;  // Compute length plus one for null terminator
  //  Now line 10 becomes: 
  user.surname=(title *)malloc( char[len] ));  // which is still wrong.
  //  char does not belong inside a malloc statement.
  //  user is a pointer, so you need pointer syntax:
  user->surname  
  //  You can't assign a pointer to surname.  It's a char array, not a pointer.  


There's a simpler way to do this.

 
  user = new title;


Don't forget to delete user, otherwise you will have a memory leak.
Which begs the question, why is user a pointer in the first place?
Last edited on
my silly mistake the buffer size. it should be 21 the buffer size.

malloc demands a pointer, the return value of malloc is an address and thus i have to store it in a pointer., maybe i should define user not as a pointer, my mistake.

Sure there is an easy way to do things... but i would like to understand the syntax char[...] inside the strlen, forget about the malloc.
The code is just a sample to showcase my problem with the weird syntax of char[...], i do not know any keywords to google and find out more :(


edit: i think i found by accident the answer :
sizeof(char[strlen(buffer)+1] ) for this weird char[...] it means find the size of an array of data type char.
Last edited on
Topic archived. No new replies allowed.