Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Pointers to Undefined Structs are Sometimes Illegal in C and C++

Tags:

c++

c

pointers

Why is

void foo(T*);

illegal in both C and C++ (because T is undefined), whereas

void foo(struct T*);

is valid, even though it still does not define T? Is there any situation in which it makes a semantic difference to the caller whether T is a struct or some other type (class/enum/typedef/etc.)?

like image 663
user541686 Avatar asked May 03 '11 21:05

user541686


People also ask

What are the illegal use of pointers list and explain?

That means a pointer initialized as an integer can only store an address of integer datatype. So when used for pointing(storing address) another datatype than initialized datatype illegal pointer error can occur.

Can you have a pointer to a struct in C?

Similarly, we can have a Pointer to Structures, In which the pointer variable point to the address of the user-defined data types i.e. Structures. Structure in C is a user-defined data type which is used to store heterogeneous data in a contiguous manner.

Are pointers allowed in structure?

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 ( -> ).

Why do we use pointers for structs in C?

Structure pointer points to the address of the structure variable in the memory block to which it points. This pointer can be used to access and change the value of structure members. This way, structures and pointers in C can be used to conveniently create and access user-defined data types.


1 Answers

void foo(struct T*); simultaneously functions as a forward-declaration of struct T within that scope, so it's safe to name a pointer to it.

In void foo(T*) there is no telling what T is supposed to be. If it turns out to be the name of a variable rather than a type, then the line of code is ill-formed. C++ needs more information before it can say that the line of code is valid.

like image 151
Lightness Races in Orbit Avatar answered Oct 21 '22 10:10

Lightness Races in Orbit