473,796 Members | 2,569 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need help - pointers

Hi There,
I'm writing a program that takes a decimal number and returns it's
binary equivalent.
the problem is that I don't know how to return (from function) the
binary value as an array of cocatenated characters. For example : I
want to convert number 3 using 4 bits, ie 3 <----"0011".
After executing, I'm getting this warning:
warning: return from incompatible pointer type
line:49: warning: function returns address of local variable

Here it is my code:

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

int power (int base, int m);
char* dec2bin(int input, int m);

int main ()
{
int input = 0;
int m = 0;

printf("Number to convert\n");
scanf("%d", &input);
printf ("Number of bits\n");
scanf ("%d",&m);
printf("input %d is converted to %s\n",input,dec 2bin(input, m));
exit (0);
}

char* dec2bin(int input, int m)
{
static int i = 0;
char* array[m+1];
int limit = 0;
limit = power(2, m);
const int MASK = limit/2; // the binary equivalent is: 1 + m 0 bits

array[m] = '\0';
for (i= 0; i < m ;i++)
{
if (input & MASK){
strcpy(array[i],"1");}
else{
strcpy(array[i],"0");}
input = input << 1;
}
return (array);
}

int power (int base, int m)
{
static int i;
int p=1;
for (i = 1; i <= m; ++i)
{
p =p * base;
}
return p;
}
Aug 11 '08 #1
12 1639
Nezhate wrote:
Hi There,
I'm writing a program that takes a decimal number and returns it's
binary equivalent.
the problem is that I don't know how to return (from function) the
binary value as an array of cocatenated characters. For example : I
want to convert number 3 using 4 bits, ie 3 <----"0011".
After executing, I'm getting this warning:
warning: return from incompatible pointer type
line:49: warning: function returns address of local variable

Here it is my code:

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

int power (int base, int m);
char* dec2bin(int input, int m);

int main ()
{
int input = 0;
int m = 0;

printf("Number to convert\n");
scanf("%d", &input);
printf ("Number of bits\n");
scanf ("%d",&m);
printf("input %d is converted to %s\n",input,dec 2bin(input, m));
exit (0);
}

char* dec2bin(int input, int m)
{
static int i = 0;
char* array[m+1];
int limit = 0;
limit = power(2, m);
const int MASK = limit/2; // the binary equivalent is: 1 + m 0 bits

array[m] = '\0';
for (i= 0; i < m ;i++)
{
if (input & MASK){
strcpy(array[i],"1");}
else{
strcpy(array[i],"0");}
input = input << 1;
}
return (array);
}

int power (int base, int m)
{
static int i;
int p=1;
for (i = 1; i <= m; ++i)
{
p =p * base;
}
return p;
}
This is the simplest fix
which only addresses the one issue raised by your compiler:

#include <limits.h>

char* dec2bin(int input, int m)
{
static int i = 0;
static char array[sizeof input * CHAR_BIT + 1];
int limit = power(2, m);
const int MASK = limit/2; // the binary equivalent is: 1 + m 0 bits

array[m] = '\0';
for (i= 0; i < m ;i++)
{
if (input & MASK){
array[i] = '1';
} else {
array[i] = '0';
}
input = input << 1;
}
return (array);
}

--
pete
Aug 11 '08 #2
Nezhate said:
Hi There,
I'm writing a program that takes a decimal number
No such thing. Numbers are numbers. Decimal is a positional notation
system. Numbers can be represented in lots of different ways.
and returns it's binary equivalent.
Here's one way:

#include <limits.h>
#include <stddef.h>

char *dec2bin(int n)
{
static char bin[sizeof n * CHAR_BIT + 1];
size_t b = sizeof n * CHAR_BIT;
size_t i = 0;

while(b-- 0)
{
bin[i++] = '0' + !!(n & (1 << b));
}

return bin;
}

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Aug 11 '08 #3
Richard Heathfield wrote:
Nezhate said:
>Hi There,
I'm writing a program that takes a decimal number

No such thing. Numbers are numbers. Decimal is a positional notation
system. Numbers can be represented in lots of different ways.
>and returns it's binary equivalent.

Here's one way:

#include <limits.h>
#include <stddef.h>

char *dec2bin(int n)
{
static char bin[sizeof n * CHAR_BIT + 1];
CMIIW. If the + 1 is for the '\0' terminator, don't we need that
terminator there?
size_t b = sizeof n * CHAR_BIT;
size_t i = 0;

while(b-- 0)
{
bin[i++] = '0' + !!(n & (1 << b));
}

return bin;
}
Aug 11 '08 #4
Iman S. H. Suyoto said:
Richard Heathfield wrote:
>Nezhate said:
>>Hi There,
I'm writing a program that takes a decimal number

No such thing. Numbers are numbers. Decimal is a positional notation
system. Numbers can be represented in lots of different ways.
>>and returns it's binary equivalent.

Here's one way:

#include <limits.h>
#include <stddef.h>

char *dec2bin(int n)
{
static char bin[sizeof n * CHAR_BIT + 1];

CMIIW. If the + 1 is for the '\0' terminator, don't we need that
terminator there?
Yes, and it's there. From 3.5.7 (Initialization ):

"If an object that has static storage duration is not initialized
explicitly, it is initialized implicitly as if every member that has
arithmetic type were assigned 0 and every member that has pointer type
were assigned a null pointer constant. If an object that has
automatic storage duration is not initialized explicitly, its value is
indeterminate."

Since the object in question has static storage duration, every member
thereof (less any that are explicitly initialised, which doesn't apply
here) is given the value 0. Note that the above passage also makes it
clear that the same guarantee does *not* apply to objects with automatic
storage duration. (It *would* apply, if the automatic object were partly
initialised - the Standard says this a few paragraphs further on.)

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Aug 11 '08 #5
On Aug 11, 6:07*am, Nezhate <ma************ @gmail.comwrote :
Hi There,
I'm writing a program that takes a decimal number and returns it's
binary equivalent.
the problem is that I don't know how to return (from function) the
binary value as an array of cocatenated characters. For example : I
want to convert number 3 using 4 bits, ie 3 <----"0011".
After executing, I'm getting this warning:
warning: return from incompatible pointer type
line:49: warning: function returns address of local variable

Here it is my code:

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

int power (int base, int m);
char* dec2bin(int input, int m);

int main ()
{
* int input = 0;
* int m = 0;

* printf("Number to convert\n");
* scanf("%d", &input);
* printf ("Number of bits\n");
* scanf ("%d",&m);
* printf("input %d is converted to %s\n",input,dec 2bin(input, m));
* exit (0);

}

char* dec2bin(int input, int m)
{
* static int i = 0;
* char* array[m+1];
* int limit = 0;
* limit = power(2, m);
* const int MASK = limit/2; // the binary equivalent is: 1 + m 0 bits

* array[m] = '\0';
* for (i= 0; i < m ;i++)
* * {
* * * if (input & MASK){
* * * * strcpy(array[i],"1");}
* * * else{
* * * * strcpy(array[i],"0");}
* * * input = input << 1;
* * }
* return (array);

}

int power (int base, int m)
{
* static int i;
* int p=1;
* for (i = 1; i <= m; ++i)
* * {
* * * p =p * base;
* * }
* return p;

}

This are the alternatives for returning a string from a function:

- Declare the array to be static, as Pete and Richard Heathfield
did
- Use a dynamic memory allocation function to allocate the array,
but remember to free() the string when you no longer need it
- Declare the function to take a pointer to an array as an
argument, and perhaps an integer representing the maximum number of
characters the buffer can hold
- Make the function operate on a global variable (yuck, don't do
this)

I'd go with the second, since it doesn't retain unneeded memory.

Sebastian

Aug 11 '08 #6
s0****@gmail.co m wrote:
This are the alternatives for returning a string from a function:

- Declare the array to be static, as Pete and Richard Heathfield
did
- Use a dynamic memory allocation function to allocate the array,
but remember to free() the string when you no longer need it
- Declare the function to take a pointer to an array as an
argument, and perhaps an integer representing the maximum number of
characters the buffer can hold
- Make the function operate on a global variable (yuck, don't do
this)

I'd go with the second, since it doesn't retain unneeded memory.
The third would be my default choice.
That way an array with any kind of duration can be used,
and if it's allocated, then the allocation and freeing
can both be done in the calling function,
which is nice from an organizational point of view.

--
pete
Aug 11 '08 #7
On Mon, 11 Aug 2008 12:02:39 +0000,
Richard Heathfield <rj*@see.sig.in validwrote:
Nezhate said:
>Hi There,
I'm writing a program that takes a decimal number

No such thing. Numbers are numbers. Decimal is a positional notation
system. Numbers can be represented in lots of different ways.
>and returns it's binary equivalent.

Here's one way:

#include <limits.h>
#include <stddef.h>

char *dec2bin(int n)
Following to your own explanation, above, shouldn't this be called
int2bin(), or maybe num2bin()?

Something called dec2bin probably should have a prototype like:

char *dec2bin(char *dec);

Martien
--
|
Martien Verbruggen | I used to have a Heisenbergmobil e. Every time
| I looked at the speedometer, I got lost.
|
Aug 11 '08 #8
Richard Heathfield <rj*@see.sig.in validwrites:
Nezhate said:
>I'm writing a program that takes a decimal number
<snip>
>and returns it's binary equivalent.

Here's one way:

#include <limits.h>
#include <stddef.h>

char *dec2bin(int n)
{
static char bin[sizeof n * CHAR_BIT + 1];
size_t b = sizeof n * CHAR_BIT;
size_t i = 0;

while(b-- 0)
{
bin[i++] = '0' + !!(n & (1 << b));
Warning: this is UB in C99 (a signed shift into the sign bit
position[1]). I presume it is OK in C90, but the wording seems vague
to me ("The result of E1 << E2 is E1 left-shifted E2 bit positions" is
all it says about shifts of signed types).
}

return bin;
}
[1] I am paraphrasing, of course (the result is defined only if 1
times 2 to the power b is representable as an int).

--
Ben.
Aug 12 '08 #9
On Mon, 11 Aug 2008 04:07:24 -0700 (PDT), Nezhate
<ma************ @gmail.comwrote :
>Hi There,
I'm writing a program that takes a decimal number and returns it's
binary equivalent.
the problem is that I don't know how to return (from function) the
binary value as an array of cocatenated characters. For example : I
want to convert number 3 using 4 bits, ie 3 <----"0011".
After executing, I'm getting this warning:
warning: return from incompatible pointer type
line:49: warning: function returns address of local variable

Here it is my code:

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

int power (int base, int m);
char* dec2bin(int input, int m);

int main ()
{
int input = 0;
int m = 0;

printf("Number to convert\n");
scanf("%d", &input);
printf ("Number of bits\n");
scanf ("%d",&m);
printf("input %d is converted to %s\n",input,dec 2bin(input, m));
exit (0);
}

char* dec2bin(int input, int m)
{
static int i = 0;
char* array[m+1];
This defines an array of pointers, not an array of char which you
need.

You have a C99 compiler which allows you to use variable length
arrays?
int limit = 0;
limit = power(2, m);
const int MASK = limit/2; // the binary equivalent is: 1 + m 0 bits
Not after you divide by 2. The binary equivalent has only m-1 zero
bits after the one.
>
array[m] = '\0';
This sets array[m] to NULL.
for (i= 0; i < m ;i++)
{
if (input & MASK){
strcpy(array[i],"1");}
This invokes undefined behavior. array[i] does not point to memory
you own. It was never assigned a value so it is indeterminate.
else{
strcpy(array[i],"0");}
input = input << 1;
Using this approach with a large input and 32 bit int will invoke
undefined behavior when a 1 bit is shifted into the sign bit.
}
return (array);
return is a statement, not a function. The parentheses are
unnecessary.

The expression array has type array of pointer to char. By rule, it
is converted to the address of the first element of the array with
type pointer to array element (essentially &array[0]). In this case,
element type is char* so the expression is converted to type char**.
char** is incompatible with the specified return type (char*) of the
function. And since array is an automatic variable in the function,
it ceases to exist once the function exits so any attempt by the
calling program to evaluate this address invokes undefined behavior.
>}

int power (int base, int m)
{
static int i;
What do you think the static buys you?
int p=1;
for (i = 1; i <= m; ++i)
{
p =p * base;
}
return p;
}
--
Remove del for email
Aug 12 '08 #10

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

Similar topics

3
1945
by: Tommy Lang | last post by:
I am working on this project and I need some help/pointers/comments to get me started, I am stuck. The program will be used to store information in an array while it is running. I need to store objects of my classes Person(superclass), Student(inherit Person), Teacher(inherit Person) in that array. The name will be the unique key. These classes are all working ok. I want to be able to add, remove, find etc. objects. To all of this, I...
9
2845
by: Simon | last post by:
Hi, if I have a structure like... struct sMyPointers{ ClassA *m_pPointerA; ClassB *m_pPointerB; void *m_pPointerToSomethingElse; };
0
2610
by: rokuingh | last post by:
ok, so i've been working on this one for quite a while, and the code is very big so i'm just going to give the relevant parts. this is a program that builds polymers (chemical structures of repeated monomers) which are represented as doubly pointed noncomplete binary trees. There are three different types of monomers (hence the three different constructer calling functions) the first one is the "leaves" of the tree, the second adds length...
1
1787
by: ArcInversion | last post by:
Hi, I've been using a javascript script to create a dragon that flies across the page. Anyways, I'd like to make it so when you click the dragon it takes you to a new page. Was wondering if anyone could help me out here. Below is the complete script. <SCRIPT language="JavaScript1.2"> var cursorpath="http://i68.photobucket.com/albums/i9/worklog_halcyon/Misc/pet1_lohi_dog.png" if (document.layers)
23
2553
by: vinod.bhavnani | last post by:
Hello all, I need desperate help Here is the problem: My problem today is with multidimensional arrays. Lets say i have an array A this is a 4 dimensional static array.
11
1533
by: sarathy | last post by:
Hi, I have been using C++ for a while. I am not entirely clear with the concepts of reference in C++. - Why was there a need for introducing a concept called "Reference" in C++ when everything was working fine with normal pointers? - Is there anything that a reference can do that a pointer cannot ??? Please clarify,
5
3375
by: Y2J | last post by:
I am working through this book on C++ programming, the author is speaking of using linked lists. He gave and example which I found confusing to say the least. So I rewrote the example in a way that I could better understand the concept, he was trying to convey to me. I ran my own example and it crashed and burn "what a surprise!" : (. I ran the authors example out of the book and quess what, it crashed also, : 0. I ran them both on my...
20
4652
by: Martin Jørgensen | last post by:
Hi, I'm reading a number of double values from a file. It's a 2D-array: 1 2 3 4 5 6 7 ------------- 1 3.2 2 0 2.1 3 9.3 4
7
1402
by: DDP3000 | last post by:
void F(int **A, int N) { int i,j; for(i=0;i<N;i++) for(j=0;j<N;j++) A=((i+j)%2==0)?1:-1; } I have never used such a thing before, so it might be a really stupid question but I cannot find the answer.
0
9680
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
9528
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
10228
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10006
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
9052
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
6788
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
5441
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...
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2925
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.