C atol() function

C atol() function - Convert a string to a long integer

The atol() function is used to convert a character string to a long value.


long int atol(const char *str)


Name Description Required /Optional
str String to be converted. Required

Return value from atol()

  • Returns a long value.

Example: atol() function

The following example shows the usage of atol() function.

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(void)
    char    *str = NULL;
    long    value = 0;
    // string value with leading and trailing white spaces.
    str = "  -7435 ";
    value = atol( str );
    printf( "Function: atol( \"%s\" ) = %d\n", str, value );

    // string value with an arbitrary decimal point.
    str = "732946.45";
    value = atol( str );
    printf( "Function: atol( \"%s\" ) = %d\n", str, value );

    // Another example with an overflow condition occurring.
    str = "234243820342342-422348";
    value = atol( str );
    printf( "Function: atol( \"%s\" ) = %d\n", str, value );
    if (errno == ERANGE)
       printf("Overflow condition occurred.\n");


Function: atol( "  -7435 " ) = -7435
Function: atol( "732946.45" ) = 732946
Function: atol( "234243820342342-422348" ) = 598985798

C Programming Code Editor:

Previous C Programming: C atoi()
Next C Programming: C strtod()

Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

Returning an array using C

You can't return arrays from functions in C. You also can't (shouldn't) do this:

char *returnArray(char array []){
 char returned [10];
 //methods to pull values from array, interpret them, and then create new array
 return &(returned[0]); //is this correct?

returned is created with automatic storage duration and references to it will become invalid once it leaves its declaring scope, i.e., when the function returns.

You will need to dynamically allocate the memory inside of the function or fill a preallocated buffer provided by the caller.

Dynamically allocate the memory inside of the function (caller responsible for deallocating ret)

char *foo(int count) {
    char *ret = malloc(count);
        return NULL;

    for(int i = 0; i < count; ++i) 
        ret[i] = i;

    return ret;

Call it like so:

int main() {
    char *p = foo(10);
    if(p) {
        // do stuff with p

    return 0;

Ref : https://bit.ly/3yFIeao

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook