Answer the question
In order to leave comments, you need to log in
What is the difference between pointers in C?
Greetings, I can’t figure out on my own what is the difference between the two methods of use, for example: obj.show_name
and obj->show_name
Let's say we have a data structure:
typedef struct users
{
char* name;
char* password;
}user_t;
user_t mt1;
user_t *mt2;
int main()
{
mt1.name = "Andrey";
mt1.password = "Password";
mt2 = malloc(sizeof(user_t));
mt2->name = strdup("Andrey");
mt2->password = strdup("Password");
mt1.name = NULL;
mt2.password = NULL;
free(mt2->name);
free(mt2->password);
return 0;
}
Answer the question
In order to leave comments, you need to log in
There is a concept of a stack. The stack is small: it is better not to allocate large objects on it. Therefore, a heap is also needed - memory is allocated there using malloc.
In addition, the lifetime of objects differs in the first and second cases. An object allocated on the stack lives until the end of the scope (usually until the closing curly brace). An object allocated on the heap lives until it is explicitly deleted (using the free method you forgot to call). Those. such dynamically allocated objects are also handy if you need to pass the object itself and/or manage its lifetime to another part of the program.
Well, if you want to modify any object (no matter how created) in some third-party function, then you need to pass a pointer to this object. As far as I remember, there are no references in C.
PS
For C, read K&R better.
There is also the symbol & which allows you to describe variables, access to which is syntactically no different from direct access, but in fact it is a link:
class MyClass
{
public int value;
MyClass(int _value):value(_value){}
}
MyClass *tmp=new MyClass(10);
MyClass &object=*tmp;
object.value=20;
delete(tmp);
Everything is simple.
Try how to dynamically allocate memory using only mt1 :) (Hint: it won’t work. You can still allocate memory through malloc using sizeof struct, but assigning the address of the beginning of the area to the mt1 variable will work)
Structures are an awesome tool for scheduling memory, especially when reading binary files with a fixed structure inside - counted N bytes into the area, imposed a structure on this area - and that's it, you can access the fields. That, actually in an example at you also becomes.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question