function definition in C - c

I can't get that why are we using a * in a function declaration like:
struct node *create_ll(struct node *)
{
body here
}
Why do we use that * before create_ll which is the function name?
And it is called using the statement:
start = create_ll(start);
If this could help.
Please explain this.

struct node *create_ll(struct node *)
means the return type of this function will be a pointer of type struct node. read it like
struct node * ,
not like
*create_ll.
This has nothing to do with the NAME of the function.

As stated by Sourav (thought I'd elaborate further, and I can't comment due to low rep), using the * operator returns a pointer to the given type, this pointer is actually just a number that stores the starting memory address of the given object (the actual type of number depends on OS and processor... 32bit numbers on a 32bit OS/processor, 64bit numbers on a 64bit OS/processor) and not the actual object itself.
For instance: even if you have a 64bit processor, if you're running Windows XP (32bit) then the resulting number will be a 32bit number (4 bytes of memory to store), if you switched over to a 64bit OS then the resulting number would be a 64bit number (8 bytes of memory to store).
In order to get a pointer in the first place, the & operator is needed... unless dynamically allocated using malloc() or something similar.
When actually using the pointer, then the -> operator is used (instead of using the . operator).
To give an example in code:
struct test_object
{
unsigned int value;
};
void function()
{
// Declare a POINTER to an object of type <test_object>
test_object *pointer;
// Declare 2 temporary objects
test_object object1, object2;
// Set object1's value using the . operator
object1.value = 1;
// Set object2's value using the . operator
object2.value = 2;
// Set the pointer to point at object2
// Note the usage of the & operator
pointer = &object2;
// Print out whatever the pointer points to (in this case object2)
// Note the usage of -> instead of .
// This is how pointers access the object being pointed at
cout << pointer->value;
// Now set the pointer to point at object1
pointer = &object1;
// Print out whatever the pointer points to (in this case object1)
// Note this is the EXACT same line used above
// but the end result is completely different
cout << pointer->value;
};
A word of warning, pointers can be quite dangerous if used incorrectly. In the above example, I didn't initialize the pointer when I declared it...
IE:
test_object *pointer = NULL;
If you tried to use the COUT line in the above code without setting the pointer first, then really bad stuff can happen (program crashes, accessing the wrong memory location giving unexpected results, etc).
The best way to avoid such things is to ALWAYS initialize pointers to NULL, and ALWAYS check if the pointer is NULL before actually trying to access the memory being pointed to...
Re-using the above code, but making it safer:
void function()
{
// Declare the pointer
test_object *pointer = NULL;
// Declare the 2 actual objects
test_object object1, object2;
// Set values
object1.value = 1;
object2.value = 2;
// Check if pointer isn't pointing at anything
if (pointer == NULL)
{
// At this moment in time, it doesn't point at anything (it's still NULL)
// So this code WON'T run, which stops the program crashing
// Print out whatever the pointer points to
cout << pointer->value;
}
// Set the pointer to point at object2
pointer = &object2;
// Check if pointer isn't pointing at anything
if (pointer == NULL)
{
// Now it DOES point to something (anything other than NULL)
// Print out whatever the pointer points to
cout << pointer->value;
}
};
If you comment out the 2 if statements, then the program will probably crash when the first COUT is reached (it SHOULD crash, but not always).
I hope this answers your question

Here * means you are using pointers.Reason is that since Node could contain lot of variables and it would consume lot of memory So to avoid this we use pointers like
struct Node*
Since in this case when calling function and passing argument or returning argument of type Node you save lot of memory since in pointers only the address of the Node is passed or returned.Otherwise huge copy(If Node have lot of variables) of the Node will be made in memory before passing to or returning from the functions.
It is just like if I take you to an apple store and go with you to buy them and in the pointer case I tell you only the address of the shop and you buy yourself.
Now coming to second part of your question struct Node*
here function will return pointer of type struct Node so to use this you will write following code.
struct Node* someInput;
sturct Node* someOutput=create_ll(someInput);
and to use members inside someOutput for example if there are members like name and age inside Node you will do following
someOutput->age;
someOutput->name;

Your function is returning a pointer.
In this case it is returning a pointer of type struct node.
so the function prototype looks like
struct node *func(struct node *);

Related

Linked List function explanation, subscription of a structure pointer

Programming a simple singly-linked-list in C, I came about this repository on Github: https://github.com/clehner/ll.c while looking for some examples.
There is the following function (_list_next(void *)):
struct list
{
struct list *next; // on 64-bit-systems, we have 8 bytes here, on 32-bit-systems 4 bytes.
void *value[]; // ISO C99 flexible array member, incomplete type, sizeof may not be applied and evaluates to zero.
};
void *_list_next(void *list)
{
return list ? ((struct list *)list)[-1].next : NULL; // <-- what is happening here?
}
Could you explain how this works?
It looks like he is casting a void pointer to a list pointer and then subscripting that pointer. How does that work and what exactly happens there?
I don't understand purpose of [-1].
This is undefined behavior that happens to work on the system where the author has tried it.
To understand what is going on, note the return value of _ll_new:
void * _ll_new(void *next, size_t size)
{
struct ll *ll = malloc(sizeof(struct ll) + size);
if (!ll)
return NULL;
ll->next = next;
return &ll->value;
}
The author gives you the address of value, not the address of the node. However, _list_next needs the address of struct list: otherwise it would be unable to access next. Therefore, in order to get to next member you need to find its address by walking back one member.
That is the idea behind indexing list at [-1] - it gets the address of next associated with this particular address of value. However, this indexes the array outside of its valid range, which is undefined behavior.
Other functions do that too, but they use pointer arithmetic instead of indexing. For example, _ll_pop uses
ll--;
which achieves the same result.
A better approach would be using something along the lines of container_of macro.

double linked list in c send data from function

This is my code:-
typedef struct Frame
{
char* name;
unsigned int duration;
char* path; // may need to scan (with fgets)
}frame_t;
typedef struct Link
{
frame_t* frame;
struct Link* next;
}link_t;
void addNewFrame(void)
{
link_t* newLink = (link_t**)malloc(sizeof(link_t*));
printf(" *** Creating new frame ***\n\n");
printf("Please insert frame path:\n");
// newLink->frame->name = (char*)malloc(sizeof(char) * MAX_LEN);
fgets(newLink->frame->name, MAX_LEN,stdin);
printf("%s", newLink->frame->name);
}
I just need to add a data to name variable in the "Frame" link list, please help me by reviewing this code.
You want to allocate the right types here:-
link_t* newLink = malloc(sizeof(link_t)); //Pointer to Link st
if(newLink){
newLink->frame = malloc(sizeof(frame_t)); //Pointer to frame member
if(newLink->frame){
newLink->frame->name = malloc(sizeof(char) * MAX_LEN); //Pointer to name member
if(newLink->frame->name){
//Rest of your code
}
}
}
EDIT:-
1. As pointed out in comments there's no need to cast the pointer returned by malloc()
2. Another very imp point you may want to check validity of the pointers before de-referencing them
First. You don't need to cast void * so (link_t **)malloc(... can be only malloc(....
Second. You allocated enough memory for a pointer not for a struct. I think you mean malloc(sizeof(link_t)) or even better malloc(sizeof(*newLink))
Third newLink->frame is a pointer so you need to allocate data for it too, newLink->frame = malloc(sizeof(frame_t))
Fourth newLink->frame->name is still a pointer so you need to allocate data for it too. newLink->frame->name = malloc(MAX_LEN)
The confusion that you are doing is pretty common. When you say type *something you are allocating a pointer to type in the stack. A pointer needs to point to somewhere else or NULL, or bad things happen. This applies to structures too. If your structure has a pointer member you need to point it to somewhere else. The somewhere else is where the real "type" object resides.
This also applies to arrays. If you say 'int foo[10]' you are allocating ten integers in the stack. If you say int *foo[10] you are allocating ten pointers in the stack. If you say int **foo you are allocating one pointer in the stack. Again all pointers need to be initialized, I mean, they need to point to some valid object, allocated somewhere else in the memory.
I hope this helps.
Some other points.
Always check pointer coming from malloc, if allocation failed you'll receive NULL. Dereferencing NULL will break your program.
Always initialize memory coming from malloc, fill it with zeros or something.
Don't use _t suffix, is POSIX reserved.
I didn't test any of this.

insertion in linked list -

I was reading Skeina's book. I could not understand this code. Basically what is the use of double pointer. And what is the use of *l = p? Can anyone please explain by diagram.
void insert_list(list **l, item_type x) {
list *p; /* temporary pointer */
p = malloc(sizeof(list));
p->item = x;
p->next = *l;
*l = p;
}
You shouldn't call it a "double pointer" because that would be a pointer to a double. It is a pointer to a pointer, and it is used to allow the function to alter the value of an argument which happens to be a pointer. If you're familiar with C#, it's like an out argument. In this situation the l argument used to get both IN and OUT behavior, but you may often see this used for output only.
Since this function returns type void it very well could have been written without the use of the pointer to a pointer like this:
list * insert_list(list *l, item_type x) {
{
list *p; /* temporary pointer */
p = malloc(sizeof(list));
p->item = x;
p->next = l; // note that this is not *l here
return p;
}
This change would require the code that calls the function to update it's own handle to the list since the head of the list is what's being changed.
This function performs a very simple task: it inserts a list node at
the position for which it receives a pointer. There is nothing
special about double pointers, they are just pointers to pointers. They hold the address of a pointer, which contains the address of an object.
void **l contains the address of a list * pointer. *l retrieves
this address and *l = p stores it.
malloc is used to allocate a
list structure, p receives the address of the allocated structure.
The code is somewhat sloppy as p is not checked for NULL before
dereferencing it. If malloc fails because of lack of memory, the
program will invoke undefined behaviour, hopefully stopping with a
segmentation fault or something potentially worse.
The node is initialized, its next pointer is set to the node pointed
to by the l argument, and finally the new node's address is stored
at the address passed as the l argument. The effect is simple: the node is inserted at *l.
This method is clever ad it allows the same function to insert a new node anywhere is a list. For example:
list *head = NULL;
...
/* Insert a LIST_A node at the beginning of the list */
insert_list(&head, LIST_A);
...
/* insert a LIST_B element as the second node in the list */
insert_list(&head->next, LIST_B);
...
/* find the end of the list */
list *node;
for (node = head; node->next; node = node->next)
continue;
/* insert a LIST_Z node at the end of the list */
insert_list(&node->next, LIST_Z);
The only tricky thing above is the concept of pointer itself, here is a simple overview:
Memory can be conceptualized as a (large) array of bytes, addresses are offsets in this array.
char variables by definition are single bytes,
int variables occupies a number of bytes specific to the architecture of the system, typically 4 or 8 bytes in current hardware.
Think of pointers as variables holding the address in memory of another variable. They need to be large enough to hold any valid address in the system, in current systems with more than 4 GB of physical and addressable memory, they are 64 bit long and occupy 8 bytes.
There is a special address value NULL which represents no object and is used to specify that a given pointer does not point to any real object. The address 0 is used for this purpose. malloc will return NULL if it cannot allocate the memory requested, the return value should be tested, as storing a value at this address is forbidden and usually caught as an invalid access (segmentation fault).
This summary is purposely simplistic. I used the term variable instead of object to avoid the confusion with OOP concepts.

C generic linked-list

I have a generic linked-list that holds data of type void* I am trying to populate my list with type struct employee, eventually I would like to destruct the object struct employee as well.
Consider this generic linked-list header file (i have tested it with type char*):
struct accListNode //the nodes of a linked-list for any data type
{
void *data; //generic pointer to any data type
struct accListNode *next; //the next node in the list
};
struct accList //a linked-list consisting of accListNodes
{
struct accListNode *head;
struct accListNode *tail;
int size;
};
void accList_allocate(struct accList *theList); //allocate the accList and set to NULL
void appendToEnd(void *data, struct accList *theList); //append data to the end of the accList
void removeData(void *data, struct accList *theList); //removes data from accList
--------------------------------------------------------------------------------------
Consider the employee structure
struct employee
{
char name[20];
float wageRate;
}
Now consider this sample testcase that will be called from main():
void test2()
{
struct accList secondList;
struct employee *emp = Malloc(sizeof(struct employee));
emp->name = "Dan";
emp->wageRate =.5;
struct employee *emp2 = Malloc(sizeof(struct employee));
emp2->name = "Stan";
emp2->wageRate = .3;
accList_allocate(&secondList);
appendToEnd(emp, &secondList);
appendToEnd(emp2, &secondList);
printf("Employee: %s\n", ((struct employee*)secondList.head->data)->name); //cast to type struct employee
printf("Employee2: %s\n", ((struct employee*)secondList.tail->data)->name);
}
Why does the answer that I posted below solve my problem? I believe it has something to do with pointers and memory allocation. The function Malloc() that i use is a custom malloc that checks for NULL being returned.
Here is a link to my entire generic linked list implementation: https://codereview.stackexchange.com/questions/13007/c-linked-list-implementation
The problem is this accList_allocate() and your use of it.
struct accList secondList;
accList_allocate(&secondList);
In the original test2() secondList is memory on the stack. &secondList is a pointer to that memory. When you call accList_allocate() a copy of the pointer is passed in pointing at the stack memory. Malloc() then returns a chunk of memory and assigns it to the copy of the pointer, not the original secondList.
Coming back out, secondList is still pointing at uninitialised memory on the stack so the call to appendToEnd() fails.
The same happens with the answer except secondList just happens to be free of junk. Possibly by chance, possibly by design of the compiler. Either way it is not something you should rely on.
Either:
struct accList *secondList = NULL;
accList_allocate(&secondList);
And change accList_allocate()
accList_allocate(struct accList **theList) {
*theList = Malloc(sizeof(struct accList));
(*theList)->head = NULL;
(*theList)->tail = NULL;
(*theList)->size = 0;
}
OR
struct accList secondList;
accList_initialise(secondList);
With accList_allocate() changed to accList_initialise() because it does not allocate
accList_initialise(struct accList *theList) {
theList->head = NULL;
theList->tail = NULL;
theList->size = 0;
}
I think that your problem is this:
You've allocated secondList on the stack in your original test2 function.
The stack memory is probably dirty, so secondList requires initialization
Your accList_allocate function takes a pointer to the list, but then overwrites it with the Malloc call. This means that the pointer you passed in is never initialized.
When test2 tries to run, it hits a bad pointer (because the memory isn't initialized).
The reason that it works when you allocate it in main is that your C compiler probably zeros the stack when the program starts. When main allocates a variable on the stack, that allocation is persistent (until the program ends), so secondList is actually, and accidentally, properly initialized when you allocate it in main.
Your current accList_allocate doesn't actually initialize the pointer that's been passed in, and the rest of your code will never see the pointer that it allocates with Malloc. To solve your problem, I would create a new function: accList_initialize whose only job is to initialize the list:
void accList_initialize(struct accList* theList)
{
// NO malloc
theList->head = NULL;
theList->tail = NULL;
theList->size = 0;
}
Use this, instead of accList_allocate in your original test2 function. If you really want to allocate the list on the heap, then you should do so (and not mix it with a struct allocated on the stack). Have accList_allocate return a pointer to the allocated structure:
struct accList* accList_allocate(void)
{
struct accList* theList = Malloc( sizeof(struct accList) );
accList_initialize(theList);
return theList;
}
Two things I see wrong here based on the original code, in the above question,
What you've seen is undefined behaviour and arose from that is the bus error message as you were assigning a string literal to the variable, when in fact you should have been using the strcpy function, you've edited your original code accordinly so.. something to keep in mind in the future :)
The usage of the word Malloc is going to cause confusion, especially in peer-review, the reviewers are going to have a brain fart and say "whoa, what's this, should that not be malloc?" and very likely raise it up. (Basically, do not call custom functions that have similar sounding names as the C standard library functions)
You're not checking for the NULL, what if your souped up version of Malloc failed then emp is going to be NULL! Always check it no matter how trivial or your thinking is "Ah sher the platform has heaps of memory on it, 4GB RAM no problem, will not bother to check for NULL"
Have a look at this question posted elsewhere to explain what is a bus error.
Edit: Using linked list structures, in how the parameters in the function is called is crucial to the understanding of it. Notice the usage of &, meaning take the address of the variable that points to the linked list structure, and passing it by reference, not passing by value which is a copy of the variable. This same rule applies to usage of pointers also in general :)
You've got the parameters slightly out of place in the first code in your question, if you were using double-pointers in the parameter list then yes, using &secondList would have worked.
It may depend on how your Employee structure is designed, but you should note that
strcpy(emp->name, "Dan");
and
emp->name = "Dan";
function differently. In particular, the latter is a likely source of bus errors because you generally cannot write to string literals in this way. Especially if your code has something like
name = "NONE"
or the like.
EDIT: Okay, so with the design of the employee struct, the problem is this:
You can't assign to arrays. The C Standard includes a list of modifiable lvalues and arrays are not one of them.
char name[20];
name = "JAMES" //illegal
strcpy is fine - it just goes to the memory address dereferenced by name[0] and copies "JAMES\0" into the memory there, one byte at a time.

double pointer question in C (single pointer for next, but double pointer for prev)

In the code of table.h for mysql. There are the following code
typedef struct st_table_share
{
...
struct st_table_share * next, /* Link to unused shares */
**prev;
in the text book, we usally have
sometype *next, *prev;
but here it use **prev instead of *prev. What the reason to use double pointer for prev?
It's not pointing to the previous structure, as next is, it's pointing to the pointer that's pointing to this structure.
The benefit of doing this is that it can point to either the 'next' member of the preceding structure, or it can point to the actual head pointer itself - in the case where this is the first item in the list. This means that removing the item involves "*prev = next" in both cases - there's no special case for updating the head pointer.
The downside is that you can't (easily) use it to traverse the structure backwards; so it's really designed to optimize the case where you only care about traversing forwards, but want to easily remove an arbitrary node.
it is not a "double pointer" as you mention. rather it is referred to as "de-referencing".
int x = 10;
int* prev = &x;
*prev is the address of variable x.
now lets say you need to pass the address of the pointer variable prev to another function named foo which accepts an address of a pointer as its parameter (pointer to a pointer).
void function foo(int** ptr)
{
prinft("%p", ptr); //this would print the address of prev
printf("%p", *ptr); //this would print the value (the address of x) contained inside address contained inside ptr.
printf("%d", **ptr); //this would print the value (the value of x, 10) contained at the address(address of x) contained inside address (address of prev) contained inside ptr
}

Resources