473,805 Members | 1,980 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

void pointers and scanf/printf

have i written this program correctly ?

it is giving me correct output but i am little suspicious in the
following two statements -

scanf("%d", &ptr->data) and printf("%d\n", ptr->data).

/********** LINK LIST **********/

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

typedef struct node_s
{
void *data;
struct node_s *next;

}node;
int add_to_link_lis t(node **head)
{
node *ptr;
int temp;

ptr = malloc(sizeof(n ode));

if (ptr == NULL)
{
fprintf(stderr, "Memory allocation failed\n");
return (1);
}

ptr->data = malloc(sizeof(i nt));
if (ptr->data == NULL)
{
fprintf(stderr, "Memory allocation failed\n");
return (1);
}

printf("Enter data\n");
if (scanf("%d", &ptr->data) != 1)
{
fprintf(stderr, "Error while entering data\n");
return (1);
}

ptr->next = *head;
*head = ptr;

return (0);
}

int main(void)
{
node *head = NULL;
node *ptr;
int n, i;

printf("How many numbers\n");
if (scanf("%d", &n) != 1)
{
fprintf(stderr, "Error while enterning list size\n");
return (EXIT_FAILURE);
}

for (i = 0; i < n; i++)
{
if (add_to_link_li st(&head))
{
fprintf(stderr, "add_to_link_li st failed\n");
return (EXIT_FAILURE);
}
}

ptr = head;

while (ptr != NULL)
{
printf("%d\n", ptr->data);
ptr = ptr->next;
}

return (EXIT_SUCCESS);
}
Jul 20 '08 #1
15 7071
On Jul 20, 5:53 pm, pereges <Brol...@gmail. comwrote:
have i written this program correctly ?

it is giving me correct output but i am little suspicious in the
following two statements -

scanf("%d", &ptr->data) and printf("%d\n", ptr->data).

/********** LINK LIST **********/

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

typedef struct node_s
{
void *data;
struct node_s *next;

}node;

int add_to_link_lis t(node **head)
{
node *ptr;
int temp;

ptr = malloc(sizeof(n ode));

if (ptr == NULL)
{
fprintf(stderr, "Memory allocation failed\n");
return (1);
}

ptr->data = malloc(sizeof(i nt));
if (ptr->data == NULL)
{
fprintf(stderr, "Memory allocation failed\n");
return (1);
}

printf("Enter data\n");
if (scanf("%d", &ptr->data) != 1)
{
fprintf(stderr, "Error while entering data\n");
return (1);
}

ptr->next = *head;
*head = ptr;

return (0);

}

int main(void)
{
node *head = NULL;
node *ptr;
int n, i;

printf("How many numbers\n");
if (scanf("%d", &n) != 1)
{
fprintf(stderr, "Error while enterning list size\n");
return (EXIT_FAILURE);
}

for (i = 0; i < n; i++)
{
if (add_to_link_li st(&head))
{
fprintf(stderr, "add_to_link_li st failed\n");
return (EXIT_FAILURE);
}
}

ptr = head;

while (ptr != NULL)
{
printf("%d\n", ptr->data);
ptr = ptr->next;
}

return (EXIT_SUCCESS);

}
your program don't work, have a segfault, compile with -Wall (if
you're using gcc) and try solve the errors, any doubt post here
Jul 20 '08 #2
On Jul 21, 2:23 am, voidpointer <diegorocha1... @gmail.comwrote :
your program don't work, have a segfault, compile with -Wall (if
you're using gcc) and try solve the errors, any doubt post here
Hello, Can you please check the first post again ? I have changed the
code. I got no warnings from my dmc/pellesC compilers and the outpu is
correct.
Jul 20 '08 #3
On Jul 20, 6:28 pm, pereges <Brol...@gmail. comwrote:
On Jul 21, 2:23 am, voidpointer <diegorocha1... @gmail.comwrote :
your program don't work, have a segfault, compile with -Wall (if
you're using gcc) and try solve the errors, any doubt post here

Hello, Can you please check the first post again ? I have changed the
code. I got no warnings from my dmc/pellesC compilers and the outpu is
correct.
Hello, now work but have one warning message,

In function 'add_to_link_li st':
test.c:30: warning: format '%d' expects type 'int *', but argument 2
has type 'void *'

you can solve this with a cast in your scanf, like this scanf("%d",
(int*)ptr->data)
and you have a lot of memory leak in your code, you doesn't free()d
the allocated space by malloc,
other thing, if you expect work with int, so use int, because void*
can be hard to work,
and need a lot of cast in your code
Jul 20 '08 #4
On Jul 20, 6:57 pm, voidpointer <diegorocha1... @gmail.comwrote :
On Jul 20, 6:28 pm, pereges <Brol...@gmail. comwrote:
On Jul 21, 2:23 am, voidpointer <diegorocha1... @gmail.comwrote :
your program don't work, have a segfault, compile with -Wall (if
you're using gcc) and try solve the errors, any doubt post here
Hello, Can you please check the first post again ? I have changed the
code. I got no warnings from my dmc/pellesC compilers and the outpu is
correct.

Hello, now work but have one warning message,

In function 'add_to_link_li st':
test.c:30: warning: format '%d' expects type 'int *', but argument 2
has type 'void *'

you can solve this with a cast in your scanf, like this scanf("%d",
(int*)ptr->data)
and you have a lot of memory leak in your code, you doesn't free()d
the allocated space by malloc,
other thing, if you expect work with int, so use int, because void*
can be hard to work,
and need a lot of cast in your code
only a correction, use scanf("%d", (int*)&ptr->data), sorry
Jul 20 '08 #5
On Jul 21, 3:12 am, voidpointer <diegorocha1... @gmail.comwrote :
only a correction, use scanf("%d", (int*)&ptr->data), sorry
but ptr->data is already address then why &ptr->data ?
Jul 20 '08 #6
voidpointer <di************ @gmail.comwrite s:
On Jul 20, 6:28 pm, pereges <Brol...@gmail. comwrote:
>On Jul 21, 2:23 am, voidpointer <diegorocha1... @gmail.comwrote :
your program don't work, have a segfault, compile with -Wall (if
you're using gcc) and try solve the errors, any doubt post here

Hello, Can you please check the first post again ? I have changed the
code. I got no warnings from my dmc/pellesC compilers and the outpu is
correct.

Hello, now work but have one warning message,

In function 'add_to_link_li st':
test.c:30: warning: format '%d' expects type 'int *', but argument 2
has type 'void *'
Check the code, your compiler or the message you really get. The
argument is of type void **.
you can solve this with a cast in your scanf, like this scanf("%d",
(int*)ptr->data)
This won't fix the problem.

--
Ben.
Jul 20 '08 #7
pereges <Br*****@gmail. comwrites:
have i written this program correctly ?

it is giving me correct output but i am little suspicious in the
following two statements -

scanf("%d", &ptr->data) and printf("%d\n", ptr->data).
Context:
typedef struct node_s
{
void *data;
struct node_s *next;

}node;
You are right to be. You can't use %d to scanf into a void * and the
reverse is also wrong.

If you want a linked list of ints, then 'data' should be an int. If
you want something more generic, you could use union. More generalt
still comes from keeping the data field as void *, but allocating
storage for it to point to whatever you need to store.

In the Bad Old Days, it was a common trick to smuggle small data types
into a generic list by putting them into the void * (actually I've not
seen it done since void * arrived, but the same applies). It is not a
good idea.

--
Ben.
Jul 20 '08 #8
On Jul 20, 7:15 pm, pereges <Brol...@gmail. comwrote:
On Jul 21, 3:12 am, voidpointer <diegorocha1... @gmail.comwrote :
only a correction, use scanf("%d", (int*)&ptr->data), sorry

but ptr->data is already address then why &ptr->data ?
this is only to avoid the warning message.

But as said voidpointer and Ben, if you want work with int, use int.
Jul 20 '08 #9
pereges <Br*****@gmail. comwrites:
On Jul 21, 3:12 am, voidpointer <diegorocha1... @gmail.comwrote :
>only a correction, use scanf("%d", (int*)&ptr->data), sorry

but ptr->data is already address then why &ptr->data ?
You some problems if you are asking this. I thought you'd written

scanf("%d", &ptr->data)

because you were knowingly breaking the type rules to put an int into
value into a void * object.

Both

scanf("%d", ptr->data)

and the type-correct version:

scanf("%d", (int *)ptr->data)

are wrong because they try to use an indeterminate pointer. The data
field has not been set to point anywhere. If you want data to point
to an int and then to read into it you must write:

ptr->data = malloc(sizeof(i nt));
if (ptr->data && scanf("%d", (int *)ptr->data) == 1) ...

Both what you had

scanf("%d", &ptr->data)

and the slightly better

scanf("%d", (int *)&ptr->data)

are wrong because they try to put an into a void * object. It often
works (as you have found out) but it is much better to do this:

struct node {
union {
int i;
void *vp;
} data;
struct node *next;
};

if you want to put ints into the actual nodes themselves. You then

scanf("%d", &ptr->data.i)

in a type-safe manner.

--
Ben.
Jul 20 '08 #10

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

Similar topics

5
1972
by: Vivek | last post by:
Hi, I am trying to get as much information on void pointers. How do we take help of void pointers in writing generic functions. I have seen this kind of code for many years, but now I have got a chance to write some myself. Could anybody point me to a link where I can get more info for the same, or refer me a book having more detail info.
25
9737
by: Podrzut_z_Laweczki | last post by:
Hello, I have question (or 2 :)). Is that true that for a large data using scanf/printf instead of cin/cout makes that the program runs faster? And if it is, is it legal to mix scanf/printf with C++ code? Program should execute below 1 sec and the hint is to use scanf/printf.
3
2013
by: sam | last post by:
Hello whats the use of void pointers? and when they are useful (on which conditions?) Please give me example code with some explanation. Thanks in advance.
5
2085
by: Rahul | last post by:
Hi Everyone, There was a discussion on the need of void * in C and C++. In C, it is a generic pointer which can be typecasted to and from that of other types. And it is developer's head ache to take care that the cast to and from void * is correct. C++ enhanced type cast dynamic_cast doesn't help in this case, as it needs the type information. This makes me wonder, why make a cast to void * and pass the info to other
18
319
by: bcpkh | last post by:
Hello All Hope someone can help me, please note that at first this might look as if it is posted to the wrong group but if you ignore the specifics I think it is general pointer referencing issue. I am building a plug-in library and is passed, according to the documentation the following; 'A pointer to the OCI environment handle and server context handle are
160
5736
by: raphfrk | last post by:
Is this valid? int a; void *b; b = (void *)a; // b points to a b += 5*sizeof(*a); // b points to a a = 100;
3
13137
by: sritejv | last post by:
Hello everyone, I am having a problem with typecasting void pointers.I have read the pointer basics but still cant understand why the following test code doesnt work. void *xyz; struct abcd { int a; };
0
9596
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
10104
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
9182
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...
0
6875
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
5541
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4317
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
3843
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3007
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.