Throwing errors when trying to compile code with ltoa in Linux - c

I am getting compilation errors when i tried to compile the code as shown below
#include <stdlib.h>
main()
{
int val = 10;
char buff[10];
char *ptr;
ptr = ltoa(val,buff,10);
printf("The val is %s\n",buff);
}
I get the compilation errors shown below:
[mcanj#varaprada ~]$ cc -g samp2.c
samp2.c: In function `main':
samp2.c:8: warning: assignment makes pointer from integer without a cast
samp2.c:11:2: warning: no newline at end of file
/tmp/ccifnKFx.o(.text+0x23): In function `main':
/home/mcanj/samp2.c:8: undefined reference to `ltoa'
collect2: ld returned 1 exit status.
Please let me know how to resolve this issue. Thanks and regards.

It is itoa() and not ltoa() but even itoa() is not a Standard Library function.
If you want your program to be portable use sprintf() or snprintf() in C99.

It's itoa, not ltoa. just change the call and it will be fine.

see http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/
Portability
This function is not defined in ANSI-C and is not part of C++, but is
supported by some compilers.
http://www.strudel.org.uk/itoa/
Arrgghh C/C++! It would appear that itoa() isn't ANSI C standard and doesn't work
with GCC on Linux (at least the version I'm using). Things like this are frustrating especially if you want your code to work on different platforms (Windows/Linux/Solaris/whatever).

C does not have itoa or ltoa functions, C has atoi function that converts a string pointed to to an int representation.
You have to implement the function if you want to use it.

Related

How to use printf() without any libraries in C?

I am programming a Teensy micro-controller as a part of a C course and am trying to work out the value of one of my integer variables. I have an integer variable called Contrast, which is initialised to the value of a constant defined as a hexadecimal number at the beginning of the .c file:
#define LCD_DEFAULT_CONTRAST 0x3F
int Contrast = LCD_DEFAULT_CONTRAST;
I am trying to investigate how this Contrast value is stored and displayed, if it shows up as 63 or 0x3F, and if they are interchangeable. I tried to use:
printf("%d", Contrast);
to print out the Contrast value to the terminal and I got the error implicit declaration of function 'printf'. I thought printf() was part of the built-in C library, so I am confused why this is not working.
Can anyone please tell me how I print the value of this variable to the screen?
The implicit declaration error just means your compiler proper doesn't have a declaration for printf. Unless you're also getting a linker error, the linker (linking usually follows compilation, unless you pass -c to disable it) is probably slapping the standard lib right on, in which case you can simply solve your warning by including stdio.h or less preferably by declaring int printf(char const*, ...);.
If you trully don't have the standard lib, you'll need to convert the integer to a string manually with something like:
int n = 42;
char buf[20];
char *end = buf+(sizeof(buf)-1), *p = end;
*p--=0;
if(n==0) *p=='0';
else{
while(n){
printf("%d\n", n%10);
*p--=n%10+'0';
n/=10;
}
p++;
}
and then pass it to your system's raw IO routine for which you'll need to have set up the system-entering assembly.
If you don't have a system, it'd be even more technical, and you probably wouldn't be asking this question.
printf() is declared in standard library header <stdio.h>.
You have to #include <stdio.h> to use printf(). It is a library call, much like all other library calls in C..

Array of char* and how to allocate memory for each

I have a very simple problem that I cannot seem to figure out. I have this:
char* array[10];
So, I then have 10 char* pointers on the stack. Now all I want to do is allocate memory for each pointer. As in:
array[0] = malloc(sizeof(char)*6);
And then store some characters at this location:
strncpy(array[0], "hello", sizeof("hello"));
Yet, I am getting a compile-time error at the first step of allocating the memory:
error: invalid conversion from ‘void*’ to ‘char*’ [-fpermissive]
But it works as expected at Ideone.
What am I doing wrong? I understand what I am trying to do, but I do not understand why it does not work. At each index in array there is a char*. By using the = symbol I am trying to assign each pointer to a block of memory allocated to it.
What am I doing wrong?
Compiling with g++ -g -Wall
What am I doing wrong? Compiling with g++ -g -Wall
g++ always compile a .c file as .cpp. Compile it with a C compiler (like GCC). In C++, you must have to cast the return value of malloc. In case of C, do not cast return value of malloc.
Your code is valid C, but you are compiling your code as C++, which, unike C, has no implicit conversion from void* to char*.
If you intended to compile the code as C (in which case you do not require the cast), use gcc, instead of g++. Also make sure you your file does not end with an extension that gcc interprets as C++ (.cpp, .C, .cxx or .cc). Or play it safe and use the .c extension.
If you want to make the code valid C++, you need to cast to char*:
array[0] = (char*)malloc(sizeof(char)*6);
This is probably the most visible difference between C and C++: C can implicitely convert the void* returned by malloc() to any other type, C++ can't.
Now, by compiling with g++, or by using a .cpp file name extension, you are compiling your code as C++ code, not C code. Use gcc instead and make sure that your source file ends with .c, and your code will compile fine.
An alternative solution is to add the cast that C++ requires: array[0] = static_cast<char*>(malloc(sizeof(char)*6));
As others have pointed out, C++ does not allow an implicit conversion from void * to char *.
If this is really supposed to be C++ code, I'd advise using new instead of malloc for dynamic memory allocation, and for this particular code I'd advise using a vector of string instead of an array of char *:
#include <vector>
#include <string>
...
std::vector< std::string > array;
...
array[0] = "hello"; // literal is implicitly converted to an instance of string
The string and vector implementations do all the memory management for you.
If this is really supposed to be C code, simply compile it using gcc instead of g++.
Try something like this:
array[0] = static_cast<char *>(malloc(sizeof(char)*6));
How should I cast the result of malloc in C++?

C: convert argv[1] to double

I need to pass a double to my program, but the following does not work:
int main(int argc, char *argv[]) {
double ddd;
ddd=atof(argv[1]);
printf("%f\n", ddd);
return 0;
}
If I run my program as ./myprog 3.14 it still prints 0.000000.
Can somebody please help?
My guess is you forgot to include #include <stdlib.h>. If this is the case, gcc will issue the following warning:
warning: implicit declaration of function 'atof' [-Wimplicit-function-declaration]
And give the exact output you provided: 0.000000.
As remyabel indicated, you probably neglected to #include <stdlib.h>. The reason this matters is that, without having a declaration of atof(), the C standard mandates that the return value is assumed to be int. In this case, it's not int, which means that the actual behavior you observe (getting a return value of 0) is technically unspecified.
To be clear, without the double-returning declaration, the line ddd=atof(argv[1]) is treated as a call to an int-returning function, whose result is then cast to a double. It is likely the case that the calling conventions on the particular system you're on specify that ints and doubles get returned in different registers, so the 0 is likely just to be whatever happened to be in that particular register, while the double return value is languishing, unobserved.
In C you don't require to declare a function before you use it (in contrast with C++), and if that happens (no prototype), compiler makes some assumptions about that function. One of those assumptions is that it returns int. There's no error, atof() works, but it works incorrectly. It typically get whatever value happens to be in the register where int is supposed to be returned (it is 0 in your case, but it can be something else).
P.S. atof() and atoi() hide input errors (which you can always see by adding option -Wall to your gcc compiler call: gcc -Wall test.c), so most people prefer to use strtol() and strtod() instead.

Not including stdlib.h does not produce any compiler error!

Hopefully this is a very simple question. Following is the C pgm (test.c) I have.
#include <stdio.h>
//#include <stdlib.h>
int main (int argc, char *argv[]) {
int intValue = atoi("1");
double doubleValue = atof("2");
fprintf(stdout,"The intValue is %d and the doubleValue is %g\n", intValue, doubleValue);
return 0;
}
Note that I am using atoi() and atof() from stdlib.h, but I do not include that header file. I compile the pgm (gcc test.c) and get no compiler error!
I run the pgm (./a.out) and here is the output, which is wrong.
The intValue is 1 and the doubleValue is 0
Now I include stdlib.h (by removing the comments before the #include) and recompile it and run it again. This time I get the right output:
The intValue is 1 and the doubleValue is 2
How come the compiler did not complain about not including the stdlib.h and still let me use the atoi(), atof() functions?
My gcc info:
$ gcc --version
gcc (GCC) 4.1.2 20070925 (Red Hat 4.1.2-27)
Any thoughts appreciated!
For historical reasons -- specifically, compatibility with very old C programs (pre-C89) -- using a function without having declared it first only provokes a warning from GCC, not an error. But the return type of such a function is assumed to be int, not double, which is why the program executes incorrectly.
If you use -Wall on the command line, you get a diagnostic:
$ gcc -Wall test.c
test.c: In function ‘main’:
test.c:5: warning: implicit declaration of function ‘atoi’
test.c:6: warning: implicit declaration of function ‘atof’
You should use -Wall basically always. Other very useful warning options for new code are -Wextra, -Wstrict-prototypes, -Wmissing-prototypes, -pedantic, and -Wwrite-strings, but compared to -Wall they have much higher false positive rates.
Tangentially: never use atoi nor atof, they hide input errors. Use strtol and strtod instead.
If you don't specify otherwise, I believe a C compiler will just guess that undeclared functions take the form extern int foo(). Which is why atoi works and atof doesn't. Which compiler flags were you using? I suggest using -Wall to turn on a bunch of gcc warnings, which should include referencing undeclared functions.
C allows you to call a function without having a declaration for that function.
The function will be assumed to return an int and arguments will be passed using default promotions. If those don't match what the function actually expects, you'll get undefined behavior.
Compilers will often warn for this case, but not always (and that will also depend on compiler configuration).
In C, when you use a function that was not declared, it assumes that it has the default prototype:
int FUNCTION_NAME();
Note that in C using () as prototype means it accepts any arguments.
If you compile with the flag -Wall (I recommend you to always use this flag, since it enables all recommended warnings) you will get a warning (not an error) telling you that you are using an undeclared function.
C, unfortunately, does not require functions to be prototyped (or even declared) before use -- but without a prototype, it automatically makes certain assumptions about the function. One of those is that it returns an int. In your case, atoi does return an int, so it works correctly. atof doesn't, so it doesn't work correctly. Lacking a prototype/declaration, you get undefined behavior -- typically it'll end up retrieving whatever value happens to be in the register where an int would normally be returned, and using that. It appears that in your particular case, that happens to be a zero, but it could just as easily be something else.
This is one of the reasons many people push "C++ as a better C" -- C++ does require that all functions be declared before use, and further that you specify the types of all (non-variadic) parameters as well (i.e. a C++ function declaration is like a C prototype, not like a C declaration).

why is strtof is always evaluating to HUGE_VAL?

What could be the issue here? It doesn't matter what number I choose for str, it is always 26815615859885194199148049996411692254958731641184786755447122887443528060147093953603748596333806855380063716372972101707507765623893139892867298012168192.00
char *str = "2.6";
printf("%f\n", strtof(str, (char**)NULL));
//prints 26815615859885194199148049996411692254958731641184786755447122887443528060147093953603748596333806855380063716372972101707507765623893139892867298012168192.00
whole program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *str = "2.6";
printf("%f\n", strtof(str, NULL));
return 1;
}
compile with -Wall:
test4.c:7: warning: implicit declaration of function âstrtofâ
What platform are you building for/on? The warning that you say is being emitted:
test4.c:7: warning: implicit declaration of function âstrtofâ
indicates that the compiler doesn't know that strtof() returns a float, so it's going to push an int to the printf() call instead of a double. strtof() is normally declared in stdlib.h, which you're including. But it wasn't a standard function until C99, so the exact compiler platform (and configuration/options you're using) may affect whether it's being made available or not.
strtof is defined in C99 only. It may be that passing the option -std=c99 to the compiler will fix it since default GCC (-std=gnu89) includes only a few C99 features.
Another option is to use the C89-kosher strtod. Which is probably the better option in the long run, anyways. (When do you need singles except in exceptional circumstances?)
Perhaps you've forgotten to include the correct header(s)?
#include <stdlib.h>
#include <stdio.h>
int main() {
printf("%f\n", strtof("2.6", NULL));
return 0;
}
produces:
2.600000
for me...
Given your warnings, you should try adding -std=c99 to get the C99 standard definitions from the header. By default it will assume that the return value is an int and then try to convert that to a float. This will obviously be wrong. Alternatively you could simply supply your own, correct declaration for strtof().
As the others have said, you need -std=c99. But you can also use strtod() which is string to double, and you don't need -std=c99 for that.
I was having problems with strtof() on CentOS 5.5 with glibc 2.5 unless I used -std=c99, but strtod() worked perfectly.

Resources