473,670 Members | 2,656 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Linked list with void *

Hai,
I thank those who helped me to create a single linked list with int
type. Now I wanted to try out for a void* type. Below is the code:

#include<stdlib .h>
#include<stdio. h>
#include<string .h>
#include<stddef .h>

struct node
{
void *data;
struct node *next;
};
struct node *insert(void *data,struct node **p)
{
void *temp;
struct node *q;
q = malloc(sizeof *q);
if(q == NULL)
{
printf("MEM ERROR\n");
exit(EXIT_FAILU RE);
}
else
{
temp = malloc(sizeof *temp);
if(temp == NULL)
{
printf("MEM ERROR2\n");
exit(EXIT_FAILU RE);
}
else
{
data = temp;
q ->data = data;
q -> next = *p;
q-> next = NULL;
*p = q;
return *p;
}
}
return NULL;
}

void disp(struct node *p)
{
for(;p != NULL; p=p->next)
printf("%s",p->data);
}
int main(void)
{
char *data;
int s=49,*a = &s;
struct node *p=NULL;
scanf("%s",data );
insert(data,&p) ;
disp(p);
insert(a,&p);
disp(p);
return 0;
}

OUTPUT:

lati˙˙˙˙ e

I have some questions:

1) When we use printf function to print something we use format
specifier for printing. (%s,%d etc). But when it comes to void*, do we
have a format specifier? If not then how will we print the void* in
the above type of program where the printing definition is in one
function and that function is called for the printing job?
2) The output I got is totally unexcepted. What ever I type I get the
same above out put. Why?
3) When we copy two void pointers shall we use just the assignment
operator or do we have to use memcpy, memset functions. Is the out put
in the above is different because of this being not used?

Thanks in advance.
Nov 13 '05 #1
6 9136
da***********@y ahoo.com wrote in
news:a3******** *************** ***@posting.goo gle.com:
int main(void)
{
char *data;
What does data point to? Junk, that's what. You don't own what it points
to so scanf()'ing into is very bad. Malloc() some stinking memory for it
or declare as an array sufficient to hold what you expect the use to enter
(knowing that this still leave you open to buffer overrun).
int s=49,*a = &s;
struct node *p=NULL;
scanf("%s",data );


POP! You scanf'd into some place you shouldn't.

--
- Mark ->
--
Nov 13 '05 #2
> 1) When we use printf function to print something we use format
specifier for printing. (%s,%d etc). But when it comes to void*, do we
have a format specifier? If not then how will we print the void* in
the above type of program where the printing definition is in one
function and that function is called for the printing job?
A void* is identified with %p, just as any other pointer. If you make it to
hold different data (e.g. an integer), make sure you cast it when you feed
it to printf (and use the appropriate identifier).
3) When we copy two void pointers shall we use just the assignment
operator or do we have to use memcpy, memset functions. Is the out put
in the above is different because of this being not used?


If you want to copy the pointers themselves, just use the assignment
operator. If you want to copy what they point at, use memcpy or memmove (or
strcpy for strings) - memset fills a region of memory with a certain byte.

Good luck,

--
Martijn
http://www.sereneconcepts.nl
Nov 13 '05 #3


da***********@y ahoo.com wrote:
...........snip ..........
struct node
{
void *data;
struct node *next;
};
struct node *insert(void *data,struct node **p)
{
void *temp;
struct node *q;
q = malloc(sizeof *q);
if(q == NULL)
{
printf("MEM ERROR\n");
exit(EXIT_FAILU RE);
}
else
{
temp = malloc(sizeof *temp);
...........snip .............

OUTPUT:

lati˙˙˙˙ e

I have some questions:

1) When we use printf function to print something we use format
specifier for printing. (%s,%d etc). But when it comes to void*, do we
have a format specifier? If not then how will we print the void* in
the above type of program where the printing definition is in one
function and that function is called for the printing job?
printf has different specifiers for different typed. The specifier for
void pointer is %p. However, in using the generic struct, you will
be converting the void *data to some other type. The code you write
and functions like printf will refer to this type. For example say
void *data will be pointing to a string. Then the specifier would
be %s and printf would look like this: printf("%s\n",( char *)q->data).
2) The output I got is totally unexcepted. What ever I type I get the
same above out put. Why?
The code has numerous errors. I am surprised that it compiled at all.
You have.
void *temp;
then you use function malloc.
..... malloc(sizeof *temp);
The sizeof operand, *temp, is an incomplete type and is not allowed.
3) When we copy two void pointers shall we use just the assignment
operator or do we have to use memcpy, memset functions. Is the out put
in the above is different because of this being not used?


The operations you use will depend on the data type you are using.
For example, a link list of names (strings), could be as follows.

#include<stdlib .h>
#include<stdio. h>
#include<string .h>

struct node
{
void *data;
struct node *next;
};
struct node *insertName(con st char *data,struct node **p)
{
void *temp;
struct node *q;

q = malloc(sizeof *q);
if(q != NULL)
{
temp = malloc(strlen(d ata)+1);
if(temp == NULL)
{
free(q);
q = NULL;
}
else
{
q ->data = temp;
strcpy(q->data,data);
q ->next = *p;
*p = q;
}
}
return q;
}

void dispNames(struc t node *p)
{
for(;p != NULL; p=p->next)
printf("%s\n",( char *)p->data);
}

void freeAll( struct node **p)
{
struct node *tmp, *current;

for(current = *p; current; current = tmp)
{
tmp = current->next;
free(current->data);
free(current);
}
*p = NULL;
}

int main(void)
{
unsigned i,number;
char buf[80],*s;
struct node *names=NULL;

printf("Enter the number of names to add to the list: ");
fflush(stdout);
fgets(buf,sizeo f buf, stdin);
number = atoi(buf);
putchar('\n');
for(i = 0;i < number;i++)
{
printf("Enter name #%d: ",i+1);
fflush(stdout);
fgets(buf,sizeo f buf,stdin);
if((s = strrchr(buf,'\n ')) != NULL) *s = '\0';
insertName(buf, &names);
}
puts("\n\nThe names in the list are");
dispNames(names );
freeAll(&names) ;
return 0;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa*@abowers.com base.com (remove the x)
http://www.geocities.com/abowers822/

Nov 13 '05 #4
Al Bowers <xa*@abowers.co mbase.com> wrote in message news:<bl******* *****@ID-169908.news.uni-berlin.de>...
da***********@y ahoo.com wrote:
..........snip. .........
struct node
{
void *data;
struct node *next;
};
struct node *insert(void *data,struct node **p)
{
void *temp;
struct node *q;
q = malloc(sizeof *q);
if(q == NULL)
{
printf("MEM ERROR\n");
exit(EXIT_FAILU RE);
}
else
{
temp = malloc(sizeof *temp);


..........snip. ............

OUTPUT:

lati˙˙˙˙ e

I have some questions:

1) When we use printf function to print something we use format
specifier for printing. (%s,%d etc). But when it comes to void*, do we
have a format specifier? If not then how will we print the void* in
the above type of program where the printing definition is in one
function and that function is called for the printing job?


printf has different specifiers for different typed. The specifier for
void pointer is %p. However, in using the generic struct, you will
be converting the void *data to some other type. The code you write
and functions like printf will refer to this type. For example say
void *data will be pointing to a string. Then the specifier would
be %s and printf would look like this: printf("%s\n",( char *)q->data).
2) The output I got is totally unexcepted. What ever I type I get the
same above out put. Why?


The code has numerous errors. I am surprised that it compiled at all.
You have.
void *temp;
then you use function malloc.
.... malloc(sizeof *temp);
The sizeof operand, *temp, is an incomplete type and is not allowed.
3) When we copy two void pointers shall we use just the assignment
operator or do we have to use memcpy, memset functions. Is the out put
in the above is different because of this being not used?


The operations you use will depend on the data type you are using.
For example, a link list of names (strings), could be as follows.

#include<stdlib .h>
#include<stdio. h>
#include<string .h>

struct node
{
void *data;
struct node *next;
};
struct node *insertName(con st char *data,struct node **p)
{
void *temp;
struct node *q;

q = malloc(sizeof *q);
if(q != NULL)
{
temp = malloc(strlen(d ata)+1);
if(temp == NULL)
{
free(q);
q = NULL;
}
else
{
q ->data = temp;
strcpy(q->data,data);
q ->next = *p;
*p = q;
}
}
return q;
}

void dispNames(struc t node *p)
{
for(;p != NULL; p=p->next)
printf("%s\n",( char *)p->data);
}

void freeAll( struct node **p)
{
struct node *tmp, *current;

for(current = *p; current; current = tmp)
{
tmp = current->next;
free(current->data);
free(current);
}
*p = NULL;
}

int main(void)
{
unsigned i,number;
char buf[80],*s;
struct node *names=NULL;

printf("Enter the number of names to add to the list: ");
fflush(stdout);
fgets(buf,sizeo f buf, stdin);
number = atoi(buf);
putchar('\n');
for(i = 0;i < number;i++)
{
printf("Enter name #%d: ",i+1);
fflush(stdout);
fgets(buf,sizeo f buf,stdin);
if((s = strrchr(buf,'\n ')) != NULL) *s = '\0';
insertName(buf, &names);
}
puts("\n\nThe names in the list are");
dispNames(names );
freeAll(&names) ;
return 0;
}


Sir,
Thanks for the code.It works well except that it prints the out put
in reverse order.
The function *insertName() takes only char pointer (string) as a
input. If some body wants to insert int data type then he has to
redefine a different function which takes int type as a input in its
parameter. I am trying to make the function *insertName() generic with
void pointer as a parameter. What to do? Cannot we make the whole
thing in a preprossor macro?

#define list(xxx) \
struct ann{ \
struct ann * next; \
xxx item; }*

int main(void)
{
list(int) fool1 = 10;
printf("%s\n",( int)fool1);
return 0;
}
OUTPUT:
10

Even though I am getting warning about the initialization I am getting
the output correctly! But I am not claming that the above code is
correct but may be to the point.
But we cannot make two objects with list(xxx). I don't know why?
Nov 13 '05 #5


da***********@y ahoo.com wrote:
Thanks for the code.It works well except that it prints the out put
in reverse order.
The function *insertName() takes only char pointer (string) as a
input. If some body wants to insert int data type then he has to
redefine a different function which takes int type as a input in its
parameter. I am trying to make the function *insertName() generic with
void pointer as a parameter. What to do? Cannot we make the whole
thing in a preprossor macro?
You can make a macro. But not the way you did it here.
First of all you can make the insert function generic by including
a size argument where you can allocate the size and then use memcpy
to copy. The prototype:
struct node *insert(const void *data,size_t size, struct node **p);
And the call would be like:
insert(buf,size of buf,&names);

You can use the macro for the display (printing) of the list.

#define disp(NODE,SPEC, TYPE) {struct node *tmp;\
for(tmp = NODE;tmp != NULL; tmp=tmp->next)\
printf(#SPEC"\n ",TYPE(tmp->data));}

There are probably better ways or languages to do this.

#define list(xxx) \
struct ann{ \
struct ann * next; \
xxx item; }*

int main(void)
{
list(int) fool1 = 10;
printf("%s\n",( int)fool1);
return 0;
}


Plug these ideas into your code and it appears to work.

#include<stdlib .h>
#include<stdio. h>
#include<string .h>

struct node
{
void *data;
struct node *next;
};

#define disp(NODE,SPEC, TYPE) {struct node *tmp;\
for(tmp = NODE;tmp != NULL; tmp=tmp->next)\
printf(#SPEC"\n ",TYPE(tmp->data));}

void freeAll( struct node **p);
struct node *insert(const void *data,size_t size, struct node **p);

int main(void)
{
int i,number;
char buf[80],*s;
struct node *names=NULL;

printf("Enter the number of names to add to the list: ");
fflush(stdout);
fgets(buf,sizeo f buf, stdin);
number = atoi(buf);
putchar('\n');
for(i = 0;i < number;i++)
{
printf("Enter name #%d: ",i+1);
fflush(stdout);
fgets(buf,sizeo f buf,stdin);
if((s = strrchr(buf,'\n ')) != NULL) *s = '\0';
insert(buf,size of buf, &names);
}
puts("\n\nThe names in the list are");
disp(names,%s,( char *));
freeAll(&names) ;
puts("\n******* *************** \nList of integers");
printf("Enter the number of integers to add to the list: ");
fflush(stdout);
fgets(buf,sizeo f buf, stdin);
number = atoi(buf);
putchar('\n');
for(i = 0;i < number;i++)
{
int value;
printf("Enter integer #%d: ",i+1);
fflush(stdout);
fgets(buf,sizeo f buf,stdin);
value = atoi(buf);
insert(&value,s izeof value, &names);
}
puts("\n\nThe integers in the list are");
disp(names,%d,* (int*));
freeAll(&names) ;
puts("\n******* *************** \nList of type doubles");
printf("Enter the number of doubles to add to the list: ");
fflush(stdout);
fgets(buf,sizeo f buf, stdin);
number = atoi(buf);
putchar('\n');
for(i = 0;i < number;i++)
{
double value;
printf("Enter double value #%d: ",i+1);
fflush(stdout);
fgets(buf,sizeo f buf,stdin);
value = atof(buf);
insert(&value,s izeof value, &names);
}
puts("\n\nThe numbers(2 decimal places) in the list are");
disp(names,%.2f ,*(double*));
freeAll(&names) ;
return 0;
}

struct node *insert(const void *data,size_t size, struct node **p)
{
void *temp;
struct node *q, *cur;

q = malloc(sizeof *q);
if(q != NULL)
{
temp = malloc(size);
if(temp == NULL)
{
free(q);
q = NULL;
}
else
{
q ->data = temp;
memcpy(q->data,data,size );
q ->next = NULL;
if(*p == NULL) *p = q;
else
{
for(cur = *p; cur->next; cur = cur->next) ;
cur->next = q;
}
}
}
return q;
}

void freeAll( struct node **p)
{
struct node *tmp, *current;

for(current = *p; current; current = tmp)
{
tmp = current->next;
free(current->data);
free(current);
}
*p = NULL;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa*@abowers.com base.com (remove the x)
http://www.geocities.com/abowers822/

Nov 13 '05 #6
Al Bowers <xa*@abowers.co mbase.com> wrote in message news:<bl******* *****@ID-169908.news.uni-berlin.de>...
da***********@y ahoo.com wrote:
Thanks for the code.It works well except that it prints the out put
in reverse order.
The function *insertName() takes only char pointer (string) as a
input. If some body wants to insert int data type then he has to
redefine a different function which takes int type as a input in its
parameter. I am trying to make the function *insertName() generic with
void pointer as a parameter. What to do? Cannot we make the whole
thing in a preprossor macro?


You can make a macro. But not the way you did it here.
First of all you can make the insert function generic by including
a size argument where you can allocate the size and then use memcpy
to copy. The prototype:
struct node *insert(const void *data,size_t size, struct node **p);
And the call would be like:
insert(buf,size of buf,&names);

You can use the macro for the display (printing) of the list.

#define disp(NODE,SPEC, TYPE) {struct node *tmp;\
for(tmp = NODE;tmp != NULL; tmp=tmp->next)\
printf(#SPEC"\n ",TYPE(tmp->data));}

There are probably better ways or languages to do this.

#define list(xxx) \
struct ann{ \
struct ann * next; \
xxx item; }*

int main(void)
{
list(int) fool1 = 10;
printf("%s\n",( int)fool1);
return 0;
}


Plug these ideas into your code and it appears to work.

#include<stdlib .h>
#include<stdio. h>
#include<string .h>

struct node
{
void *data;
struct node *next;
};


Thanks for the code .Btw it is not a home work.
Nov 13 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
859
by: Dream Catcher | last post by:
1. I don't know once the node is located, how to return that node. Should I return pointer to that node or should I return the struct of that node. 2. Also how to do the fn call in main for that LOCATE subroutine that returns a node???? Any help would be appreciated. Thanks
10
15121
by: Kent | last post by:
Hi! I want to store data (of enemys in a game) as a linked list, each node will look something like the following: struct node { double x,y; // x and y position coordinates struct enemy *enemydata; // Holds information about an enemy (in a game) // Its a double linked list node
1
12835
by: Booser | last post by:
// Merge sort using circular linked list // By Jason Hall <booser108@yahoo.com> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> //#define debug
6
4593
by: Steve Lambert | last post by:
Hi, I've knocked up a number of small routines to create and manipulate a linked list of any structure. If anyone could take a look at this code and give me their opinion and details of any potential pitfalls I'd be extremely grateful. Cheers Steve
4
3598
by: JS | last post by:
I have a file called test.c. There I create a pointer to a pcb struct: struct pcb {   void *(*start_routine) (void *);   void *arg;   jmp_buf state;   int    stack; };   struct pcb *pcb_pointer;
4
3591
by: MJ | last post by:
Hi I have written a prog for reversing a linked list I have used globle pointer Can any one tell me how I can modify this prog so that I dont have to use extra pointer Head1. When I reverse a LL using the recursive call how to change the last node pointer to head and head->next to null without using the extra global pointer Mayur
1
1796
by: drewy2k12 | last post by:
Heres the story, I have to create a doubly linked list for class, and i have no clue on how to do it, i can barely create a single linked list. It has to have both a head and a tail pointer, and each node in the list must contain two pointers, one pointing forward and one pointing backwards. Each node in the list will contain 3 data values: an item ID (string), a quantity (integer) and a price (float). The ID will contain only letters and...
51
8617
by: Joerg Schoen | last post by:
Hi folks! Everyone knows how to sort arrays (e. g. quicksort, heapsort etc.) For linked lists, mergesort is the typical choice. While I was looking for a optimized implementation of mergesort for linked lists, I couldn't find one. I read something about Mcilroy's "Optimistic Merge Sort" and studied some implementation, but they were for arrays. Does anybody know if Mcilroys optimization is applicable to truly linked lists at all?
0
8624
by: Atos | last post by:
SINGLE-LINKED LIST Let's start with the simplest kind of linked list : the single-linked list which only has one link per node. That node except from the data it contains, which might be anything from a short integer value to a complex struct type, also has a pointer to the next node in the single-linked list. That pointer will be NULL if the end of the single-linked list is encountered. The single-linked list travels only one...
7
5764
by: QiongZ | last post by:
Hi, I just recently started studying C++ and basically copied an example in the textbook into VS2008, but it doesn't compile. I tried to modify the code by eliminating all the templates then it compiled no problem. But I can't find the what the problem is with templates? Please help. The main is in test-linked-list.cpp. There are two template classes. One is List1, the other one is ListNode. The codes are below: // test-linked-list.cpp :...
0
8468
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8386
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8660
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7415
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6213
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5683
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4390
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2799
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1792
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.