pointer to structure and self pointers - c

What is the difference between self referential pointer in structure and pointer to structure?
struct abc
{
int data;
struct abc *next;
}
struct abc *pt;
What are the differences between *next and *pt??
How they differ in their use??
I am really in doubt between these two
I am a beginner
First example is used mainly for linked list
Are pointer to structure node and self referential pointer the same thing?
please see
see-programming.blogspot.in/2013/05/chain-hashing-separate-chaining-with.html here we have used struct hash *hashTable as an array ..how?? and can we do same with *pt

They are of the same type. They behave in the exact same way.
Some example usage:
// declare 2 structs
struct abc s1;
struct abc s2;
// point pt to s1
pt = &s1;
// point s1.next to s2
s1.next = &s2;
// access pt->data
int a = pt->data;
// access s1.next->data
int a = s1.next->data;
Differences in usage:
There's only one pt variable.
For every struct abc variable, there is a next variable.
In the context of a linked-list, there is only one head pointer, thus pt would be it.
But each node points to the next node, thus next should be used for this.
Using pointers as arrays?
Yes, this can be done with either pt or next.
A pointer just points to an address in memory. There can be any number of structs following on each other at that location.
If you want to use it as an array (or just using pointers in general), you just have to make sure you don't try to access elements that you didn't allocate memory for (with malloc for example) and free the memory after usage (if you used malloc).
Some example usage with array:
// declare a struct
struct abc s1;
// make an array of size 10
struct abc *a1 = malloc(10*sizeof(struct abc));
// give the 4th element a new value
a1[4] = s1;
// free the memory
free(a1);
I hope that helps a bit.

Conceptually, very little difference at all.
next is a member of the same structure it is pointing to. pt is not a member of the structure it is pointing to.
They are used in a similar way, except that to use next you have a have an existing struct abc, and pt can be used directly. Please consider:
myABC.next= &myOtherABC ;
pt= &myOtherABC ;
are pointer to structure node and self referential pointer same thing
They are and they are not. Depends on point of view. They are because they both point to a structure. They are not because a pointer to structure can point to any structure, and as a variable it can be a parameter, a local variable, a member of another struct, etc. But a self referential pointer is necessarily a member of a struct and points to the same struct it is a member of.

The only difference applies to people that write compilers. That is because a self-referential pointer refers to itself before itself is fully declared. So someone writing a compiler has to deal with this special case.
As a programmer (that means you), there is no difference, and the terms do not offer any additional meaning.

they are the same type but they do not contain the same value
from pt you can access next because pt point to a structure that contain next. but from next you can't access pt.
for linked list, you have to understand, that the list contain at the begining 1 element, and this element know how reach the next element of the list, it is the goal of the next pointer

There is no difference between those two pointers.
A possible difference in usage depends on the context but still does not apply to their nature of being both pointer to the same type of structure and therefore undergoing the same rules in terms of assignment, reading and arithmetics.

Related

How can is it possible to use new initialized node inside of itself?

here I use n node inside of it as "struct n *next" how is this possible or what is the meaning of it ?
struct n {
int data;
struct n *next ;
};
TLDR
It's a pointer
There is an entity in C and C++ called pointer. It is a variable contains address in memory where actual value stored. In your case you say to compiler "I want to store address of next node in this variable". struct n just type name, next is variable name and * is mark to compiler that that variable is a pointer.
If you want to learn a little more about pointers I recommend you to read great book called "Using and understanding C pointers".

C language Creating an instance and data type with Linked lists [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 2 years ago.
Improve this question
I'm studying C language with a book called Sams Teach Yourself. I understand the concept of linked lists, but cannot understand the technique. I'm going to write down how I understand this and have some questions along the way. Please let me know if I'm wrong or you know the answer to the questions. Here we go.
SECTION 1
Preliminarily, I need to define the data structure and declare the head pointer to start a linked list like below.
struct person{
char name[20];
struct person *next;
};
struct person *new;
struct person *head;
head = NULL;
In here, a simple structure is defined. Its type or tag name is person. It has 1 element, an array called name, and 1 self-referencing pointer called next. After the definition of the structure, 2 pointers are declared. One of them is initialized to NULL, because it is a good practice when there's nothing to point.
Section 1 Question
Do I understand preliminaries of the linked list correctly in section 1?
SECTION 2
The book explains that the procedure for adding a new element to the start of the list is 3-steps.
Create an instance of your structure, allocating memory space using
malloc().
Set the next pointer of the new element to the current value of the head pointer. This will be NULL if the list is empty, or the address of the current first element otherwise.
Make the head pointer point to the new element.
new = (person*)malloc(sizeof(struct person));
new->next = head;
head = new
new is assigned with malloc, which I have a question about. The valueNULL ofhead is assigned to the self-referencing pointer because it is the last pointer. Then the value of new is assigned to head the top pointer to point.
Section 2 Qustions
Where in this code is creating an instance? Isn't the format struct tag instance for creating an instance? Is new a instance? Isn't it a pointer declared in section 1?
How does sizeof(struct person) work? sizeof(char) is 1 because char is 1-byte. How could struct person have a value because it is only a tag name?
The book explains that malloc() is typecast so that its return value is the proper type - a pointer to the person data structure. I thought the data types in C were only int, char, float and variations of them. Is a pointer a data type?
In here, a simple structure is defined. Its type or tag name is person. It has 1 element, an array called name, and 1 self-referencing pointer called next. After the definition of the structure, 2 pointers are declared. One of them is initialized to NULL, because it is a good practice when there's nothing to point.
All correct, but to be 100% precise there is no "self-referencing pointer", it's just a pointer field which points to a structure of the same type, it could point to any other structure of that type.
Where in this code is creating an instance? Isn't the format struct tag instance for creating an instance? Is new a instance? Isn't it a pointer declared in section 1?
"Creating an instance" is bad wording. There is no such thing as "instancing" in C. In C, memory can be allocated in two main ways: automatically (via a variable declaration) or dynamically (via an explicit call to malloc() or similar functions).
Automatic allocation of variables happens on the stack and (as the word implies) is automatic: you do not need to worry about explicitly reserving space for the variable, the compiler does it for you, and it also frees up that space when the variable gets out of scope. Dynamic allocation is manually performed by the user, and thus also needs manual cleanup using free() to free the allocated space once it is not needed anymore.
In this case since you declared a pointer struct person *new you have automatically allocated space for the pointer itself, but you still need to allocate space for the struct if you want that pointer to point to something valid.
How does sizeof(struct person) work?
Every type has a known fixed size (almost, there are exceptions). A structure composed of multiple basic types has a size that is at least the sum of the sizes of its fields. Your struct person is a new type defined by you, which has itself a size, it's not just a "tag name". Every time you create a variable of type struct person, your program needs to allocate sizeof(struct person) bytes for it. In particular:
sizeof(struct person) >= 20 * sizeof(char) + sizeof(struct person *);
// ^^^ always 1 ^^^ usually 4 (on a 32bit system) or 8 (on a 64bit system)
The book explains that malloc() is typecast so that its return value is the proper type - a pointer to the person data structure.
The book is wrong. You do not need to cast the result of malloc(). In C, there's a special type: void: it means "no type". The associated pointer type, void *, means "a pointer to any type", and is what malloc() returns.
A pointer of type void * is guaranteed to be always castable to any other pointer type, and the conversion from/to void * to/from any other pointer type happens automatically without the need of an explicit cast. See also here for a good explanation of why casting the return value of malloc() is a bad idea.
I thought the data type in C is only int, char, float & variation of them. Is a pointer a data type?
Oh no, it's not only those. You just defined a new data type yourself (struct person). I'm surprised your book did not define what a data type is before diving into higher level stuff like linked lists and dynamic memory allocation. A pointer is indeed another basic data type in C, since you can take the address of any variable of any type, there exist as many pointer data types as non-pointer data types: int *, char *, float *, ecc. In fact, struct person * is a pointer data type, identifying a pointer to a variable of type struct person.

Unable to deal with a seems unnecessary pointer to pointer when i was reading the core code of bsd 4.4

I was reading the tcp/ip illustrated v2 and confused with a series of codes on the book.
struct ifnet{
struct ifnet * if_next;
……
}
here is the background information of the structure which may help you learn more about the problem
void if_attach(struct ifnet* ifp){
struct ifnet **p = &ifnet;
while(*p):
p = &((*p)->if_next);
*p = ifp;
why the author used a pointer to pointer in this place ? I promise that in the remaining text the p never appear again(which means it is never used as an argument of any function at all).
In my opinion this code can be converted to this
struct ifnet *p = ifnet;
while(p):
p = *p->if_next;
p = ifp;
Is that right?
The author used a pointer to a pointer because they noticed a commonality that they leveraged into an abstraction. It's "traversing the list by the links" instead of by the nodes.
You obviously know that if your linked list data structure is referenced by a pointer, then you must pass a pointer to that pointer into your function, in case insertion or deletion happens on the head node. Otherwise, you modify the internal pointers of the nodes in question.
But what if you refer to those internal node pointers by their address as well, instead of accessing them through the node they are in? Well, then the code becomes the same for both the head node and all internal nodes.

Struct points as parameter to function C

I have a few months that i started programming in C, but I now find myself with a doubt, for example, let see the next example code:
typedef struct
{
char *var1;
}myFooStruct;
myFooStruct struct1 [ 200 ];
my doubt is what would I get for **struct1, &struct1, *struct1, struct1,
as I passed the struct to a function that takes a two-dimenssion pointer ( **myFooStruct ), I have basic knowledge about pointers 1-but I find myself confused with pointers to structs and 2-how can I modify the struct if I passed it as at parameter to a function
If there is another similar question post it here please, I could not find anything alike, if you know some lecture I could read is welcome too, thank you very much!!
* is a dereference operator - think of it as meaning "the value contained at location xyz".
& is a reference operator - think of it as meaning "the location in memory of variable xyz".
Accordingly:
myFooStruct struct1 is a physical structure - this is the actual object.
&struct1 is equivalent to the location in memory of struct1 - this is usually an address (like 0xf0004782). You'll usually see this used when passing by reference (see Wikipedia for more info) or when assigning to a pointer (which literally points to a location in memory - get it?).
*struct1 dereferences struct1 - that is, it returns the value contained at location struct1. In the example you give, this is invalid, as struct1 is not a pointer to a location in memory.
**struct1 is tricky - it returns the value contained at the location that is contained within struct1. In other words: struct1 points to a certain location in memory. At that location is the address of another location in memory! Think of it as a scavenger hunt - you go to a location, find a clue, and follow that to another location.
As to how to access structs: think of a struct as a box. When you have the box in front of you, you simply need to open it up and look at what's inside. In C, we do this using the . operator:
char *my_var = struct1.var1
When you don't have the box in front of you - that is, you have a pointer to the struct - you need to access the location the box is at before you can look at what's inside. In C, we have a shortcut for this - the -> operator:
myFooStruct *pointer_to_struct1 = &struct1
char *my_var = pointer_to_struct1->var1
//NOTE: the previous line is equivalent to:
// char *my_var = (*pointer_to_struct1).var1
Way 1 Using dynamic memory allocation. Generally used in linked list and all..
If you want to modify the struct in another function. first declare a pointer to a struct.
myFooStruct* struct1;
Allot memory for the struct
struct1 = malloc(sizeof(myFooStruct));
Send the address to the function
func1(struct1);
Receive it and access it to modify in the function.
void func(myFooStruct* struct1)
{
(*struct1).member1 = ...; // whatever you wanna do
...
Way 2
Declare a struct.
myFooStruct struct1;
Send the address of the struct to the function
func1(&struct1);
Receive it and access it to modify in the function.
void func(myFooStruct* struct1)
{
(*struct1).member1 = ...; // whatever you wanna do
...
If you need to access myFooStruct from function, you can define single pointer: fn( myFooStruct * st ). The you call the function with fn( struct1 ) and change values st[N].var1 = .... Double pointer may be necessary if your object is pointer with allocated memory, not static array as yours.
struct1 is just a table and to be speciffic it's just pointer to a place in the memory.
*struct1 would be thing, that is pointed by struct1, so it's a first struct in a table of structs.
But **struct1 won't be any string. First of all you do not allocate memory for string and second string is member of this struct not struct itself. **struct is undefined behavior, nothing more.
&struct is a pointer to the table, so it's a pointer to the pointer, that points first struct in a table.
You have to decide on your own, what you want. If you want to pass table of your structs then the cleanest way would be:
void function(myFooStruct structTab[]);
1. You should pass a struct pointer to function to access struct inside it .
Declare a struct pointer -
myFooStruct *struct1;
Allocate memory for struct
And pass it to function which is declared as -
type fn(myFooStruct *struct1){
.....
}
Call this function like this -
fn(struct1);
Access struct member like this -struct->member1
2. You can also pass what you have declared right now.
myFooStruct struct1[ 200 ];
define function as -
type fn(myFooStruct struct1[]){
.....
}
Access struct members like this - struct[i].member1.

How to copy typedef struct into another one?

How to copy typedef struct into another one?
If I have a typedef struct called books and I have a struct variable called books first. Now I declare books second How can I pass the content of first to second? Is there a function to do that or I can do that just with second = first ?
If your structure does not contain any members that are pointers (or containing structs that do), then you can simply assign one to the other.
second = first;
If however your structs do contain pointers, then with a simple assignment you end up with two struct that contain pointers to the same memory, and changing one will affect the other. If that's not what you want then you need to do a deep copy.
For example:
struct book {
char *name;
int cost; // in cents, so you don't have to deal with floating point issues
};
struct book first;
first.name = strdup("title1");
first.cost = 500;
struct book second;
second.name = strdup(first.name);
second.cost = first.cost;
If both first and second have the same type, then you can just do second = first; . It does not matter whether the type is an built-in or user-defined. C will copy the contents of first over to second. Just try it.
In general, variables in C are just data with a name and a type.
If the types of 2 variables a and b match, you can assign one to the other: a = b;.
What happens is that the value of variable b is copied into variable a.
But beware of pointers: For C, pointers are just variables with a value (the fact that the value represents a memory address does not matter, C treats all data equal).
If the 2 variables happen to be pointers, like char *a; char *b; then you can assign a = b; just with any variable.
But since the value of the variable b is the memory address, the memory address is copied from b to a, not the content of the memory at the memory address.
If you want to have the memory copied over, you will have to do it on your own, e.g. via the help of memcpy() (see its man page for information).
That said, if your structs contain pointers, the pointers are the content, not the stuff the pointers point to. C would copy the pointer values, not the pointer targets.
If you got pointers in your structs and want some sort of deep-copy, you would have to implement the traversal of your structs on your own. See What is the difference between a deep copy and a shallow copy?

Resources