Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this pointer of type structure definition mean (in C)?

In K&R Chapter 6, a declaration is mentioned as follows:

struct{
    int len;
    char *str;
} *p;

I couldn't understand which structure is this pointer p pointing to and if such a pointer definition is even valid because in all other examples given in the book and the ones I have seen otherwise, when defining a pointer to a structure, the name of the structure, that is, the type being defined needs to be mentioned. For example,

struct example{
    int a;
    ...
}s1;

and then,

struct example *ptr = &s1;

so, it is mentioned that ptr is pointing to a type struct example and not just struct.

Also, of particular interest was this:

*p->str fetches whatever str points to; *p->str++ increments str after accessing whatever it points to (just like *s++);

I couldn't follow what p is in the first place, hence, not the increment and dereference as well.

What is going on here?

Thanks in advance!

P.S. I am new here, so any feedback on the format of the question would also be appreciated.

like image 536
Eulerian Avatar asked Nov 01 '17 19:11

Eulerian


People also ask

What is pointer to a structure in C?

Pointer to structure holds the add of the entire structure. It is used to create complex data structures such as linked lists, trees, graphs and so on. The members of the structure can be accessed using a special operator called as an arrow operator ( -> ).

What is structure definition in C?

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).

What is the structure at the pointer?

Structure pointer in C is declared using keyword struct followed by structure name to which pointer will point to follower by pointer name. A structure pointer can only hold the address of a variable of the same structure type used in its declaration.

What do you mean by type defined structures?

Educative Answers Team. The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g.,​ int) and user-defined​ (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.


3 Answers

The struct keyword works sort of like an extended version of typedef, except that you create a complex custom type (called a structure) instead of aliasing an existing type. If you only have one thing that needs to use the declared type, you do not need to provide an explicit name for the type.

The first statement you are looking at declares a structure with two fields, but does not name it. This is called an anonymous structure. The declaration does, however, provide a pointer of that type.

One possible use-case for such a declaration is when you make a header for an external library, possibly one that is not even written in C. In that case, the type of the structure may be opaque or incomplete, and you just need to have a convenient reference to some parts of it. Making the structure anonymous prevents you from being able to allocate it yourself easily, but allows you to interact with it through the pointer.

More commonly, you will see this notation used in conjunction with named or at least aliased structures. The second statement could be rewritten as

struct example { ... } s1, *ptr; 

In that case, struct example *ptr = &s1; would be just ptr = &s1;.

An even more common occurrence is the use of anonymous structures with typedef, create custom type names that do not include the struct keyword. Your second example could be rewritten as

typedef struct { ... } example, *pexample; example s1; pexample ptr; // alternatively example *ptr; ptr = &s1; 

Note that the type of s1 is example and not struct example in this case.

like image 193
Mad Physicist Avatar answered Oct 06 '22 01:10

Mad Physicist


For starters consider the following simple program

#include <stdlib.h>
#include <stdio.h>
#include <string.h> 

int main(void) 
{
    struct {
        int len;
        char *str;
    } *p;

    p = malloc( sizeof( *p ) );

    p->str = "Hello Nihal Jain";
    p->len = strlen( p->str );

    while ( *p->str ) putchar( *p->str++ );
    putchar( '\n' );

    free( p );

    return 0;
}

Its output is

Hello Nihal Jain

So in this declaration

    struct {
        int len;
        char *str;
    } *p;

there is declared a pointer of the type of the unnamed structure. The pointer itself is not initialized. You could write for example

    struct {
        int len;
        char *str;
    } *p = malloc( sizeof( *p ) );

For this simple program the name of the structure is not required because neither declaration of an object of the structure type is present or needed in the program.

So you can not declare an object of the structure type but it is not required in this case.

According to the C Standard structure or union are declared like

struct-or-union-specifier:
    struct-or-union identifieropt { struct-declaration-list }
    struct-or-union identifier

It is seen that the identifier is optional if there is a struct-declaration-list. So an unnamed structure can be used as a type specifier.

One more example with using enumerations. You can declare enumerators without declaring the enumeration type. For example

enum { EXIT_SUCCESS = 0, EXIT_FAILURE = -1 }; 

You can use the enumerators that have the type int without declaring an object of the enumeration type if there is no such a requirement in the program.

like image 21
Vlad from Moscow Avatar answered Oct 05 '22 23:10

Vlad from Moscow


Also another use (of anonymous structures) would be to use them inside unions or other structs which basically limits the use of that struct to that particular parents union or structure not anything else, which is quite useful from programmer's point of view because looking at a code like this it provides us with the information that it is used locally on the context of the struct or union inside it - nothing more than that. (also saves us from naming).


Also if you use this anonymous structure you wont be able to allocate one instance of it other than the one which already exists.

Example:-(stark's comment: how to use it?)

struct {
  int a;
  int b;
} p;

scanf("%d",&p.a);
like image 29
user2736738 Avatar answered Oct 05 '22 23:10

user2736738