Why do you have to access struct members with an '->'? [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Normally you access structure-members by a dot (Struct.Member), but when Struct is a pointer, you have to use Struct->Member
Is there a special reason for this? Because in both instances you're just referring to a piece of memory. And the compiler should be able to handle both operators, so is it just an enforced codestyle ?

It's because the language is defined that way.
There are languages that allow the prefix of the . operator to be either a structure or a pointer to a structure. No ambiguity is introduced because, as you say, the compiler knows what type the prefix is.
C just happens not to do that. I don't think there's any deep reason for it, it's just the way Dennis Ritchie decided to do it.
And using . for structures and -> for pointers also makes it clear to the reader whether the prefix is a pointer or not. For a relatively low-level language like C, that kind of detail can be important.

You can access the struct elements in . notation if the struct is a pointer. You just have to dereference the struct elements
So :
(*struct).element should work fine

Related

Is there a difference between an "object" and a pointer to some kind of struct? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
All of my initial programming experience has been in object-oriented languages (Java, Python). I am now learning C, and it seems that there are still things that resemble objects.
Say for example, a FILE pointer created with the standard C library. This is just a pointer to the memory location of a struct. Is this essentially the same thing as an object in OO languages?
There are existing questions asking about the difference between a struct and a class, but I'm asking about how a program uses those things. A struct is used or accessed via a pointer, while an object is a particular instance of a class. In this sense, it seems that a class is more general than a struct. Though I really only added this paragraph to prevent this questions from being marked as a duplicate, and it strays from my original question.
If a FILE pointer is, indeed, comparable to some FILE object in a different language, then where is the key difference between how that "thing" called FILE will be handled in a object-oriented language vs a non-object-oriented language. Seems like the line starts to blur.
In the C programming language, an object is a “region of data storage in the execution environment, the contents of which can represent values” (cf ISO 9899:2011 §3.15). Almost everything is an object, including pointers, arrays, structures, and integers (but not functions).
This notion however is different from what you understand as an “object” in most object-oriented languages. Notably, objects in C don't have behaviour associated with them, don't have classes and don't have any guarantees whatsoever. There isn't even a guarantee that an object may represent any value at all. An object is only a bit of memory.
The typical API design pattern in procedural programming languages like C is that there is a set of functions (like fopen, fprintf, fclose, fwrite, etc.) and a set of structure types (like FILE) that collect data required for these functions. The association between these structures and the corresponding behaviour is made by passing structures to functions.
You can build all the things you have in an object-oriented language like that, including virtual function calls and classes, you just have to build all of this manually. I believe this is a strength of C as you are not forced into a certain program structure, you can apply the design pattern of object-orientation where appropriate and use other approaches where not.

What is the advantage of using pointers in C? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Why do we use pointers in C Programming?
In general pointers are able to access the address where the int/float/char etc... is stored.
Are there any other uses?
It depends on what you try to achieve:
you can change the value of a variable inside a function
you can pass a struct to a function without having to copy all its fields - think of a function that receives a struct.
you can point to a specific variable/struct and point to it from other structs
and many other advantages (advantages is purpose dependant and it depends on whats your program is doing).
Pointers are quite basic C and there is a lot of material online you should get yourself familiar with them and the advantages will pop up themselves.
The reason is that pointers are used to bodge into C some vital features which are missing from the original language: arrays, strings, & writeable function parameters. They can also be used to optimize a program to run faster or use less memory that it would otherwise. A few tasks these days, such as programming microcontrollers, still need this.

Use C++ possibilities in C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
It might be a silly question, but I'm interested in it very much. Is it possible to implement operator new, dynamically expanding arrays, classes in pure C?
Any links or code examples will be appreciated.
new: #define new(type) malloc(sizeof(type)) (have to call it using function syntax, like struct stat *st = new(struct stat))
dynamically expanding arrays: realloc plus some custom array-manipulation functions (like push_back, etc.) - this is commonly implemented by third-party C utility libraries (and, as #Mgetz points out, some compilers have built-in extensions for it)
classes: structs with function pointer members (this is very common in several projects, such as the Linux kernel)
You might want to look at GObject, which is a C library providing some object-oriented features to C. Also see the dozens of hits you get for googling "Object-Oriented C".
A quick google search revealed this:
http://ooc-coding.sourceforge.net/
Haven't read it through but it sounds like what you're after.
Yes, it is possible (common?) to implement object orientedness in C - or at least the bits that are especially needed.
An example is a once created a garbage collector by storing the pointers to malloced memory and the free function in linked lists.
The best thing about C is that it just works and there is almost zero overhead. The more work a language does for you automatically can mean there is a lot more overhead - though this is not always the case.
It depends if it is OK for you to reimplement the compiler.
If it's ok - you can do whatever you wish, otherwise:
new - as an operator - no, but you can define a function + macros that will simulate it.
classes - yep, you can. you may simulate it pretty closely with static functions and an array of pointers to functions. But there will be no overloading.
expanding arrays - yes, with the classes simulation above.

How does struct works under the hood? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am curious about struct that we declare in C. What does it actually do ?
I know we can make nodes & pointers to those using struct but how does it function ? Like a while loop checks the condition & branches accordingly if equal or not equal. What does struct do under the hood ?
A struct type is a user-defined composite type. It is composed of fields or members that can have different types.
From struct-wiki:
A struct in the C programming language is a declaration that defines a list of variables to be placed under one name in a block of memory, allowing the different variables to be accessed via a single pointer.
For memory allocation of a struct: check out How are C struct members allocated?
For why to use struct, check out Why should we typedef a struct so often in C?
Its nothing more than multiple variables treated as one entity. There is not much magic behind this, the values simply appear behind each other in the order of declaration in the memory.
A C struct simply represents data in a specified way and doesn't do anything at all. It is used to represent a more complex data-type, such as a linked-list node.
Using struct a user can define its own required data type to handle complex data.
just like array where all elements in array are of same type but in struct each element can be defined in user's desired way.
so struct is used to define ""user-defined data types".

C standard conforming way to do struct alignment [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is there a C standard conforming way to do struct alignment?
I know that one could put the biggest elements first but I am in a situation where I am about to implement a protocol.
No, not in general.
You absolutely cannot change the order of elements in a structure, they have to be in the exact order as declared.
But you also cannot know in advance what some future processor will prefer, in terms of alignment.
Protocols (which are "external" representations) should never involve directly copying to/from a struct in memory; instead you must serialize/deserialize each struct member on its own.
For implementing a protocol, it is best to serialize the values as needed and deserialize them as well.
This retains compatibilty across architectures with varying data field sizes, alignment requirements and endianness.
You can specify alignment in C11 with the _Alignas keyword (see also stdalign.h). You can look it up in the draft of the C11 standard that is freely available.
Depending on some kind of directive is probably not a good idea. I would not do it. Custom serializers/deserializers are the standard here.
I suggest writing a simple parser that would process a struct declaration and prepare a set of serialize/deserialize functions. If it is a simple plain old data structure, the parser and code generator will be very simple and efficient.
It sounds like you plan to do something like a union overlay to encode / decode the protocol. This is a bad idea. It is much better to do a proper serialise / deserialise, field by field.
This is much more portable.

Resources