Get This Book -> Matrix Problems: For Interviews and Competitive Programming
<stdlib.h>is the header ofGeneral Purpose Standard LibraryVonprogramming language cwhich declares a variety of utility functions for type conversions, memory allocation, process control, and other similar tasks. It also has various data types and macros defined in the header.
To use this header in C, you must write the following line at the top of your C program:
#incluir <stdlib.h>
#include <x/*y> specifies that a system header file named x/*y should be included.
This header can also be used in C++cstdlib.
On this page we describe all the functions, data types and macros defined instdlib.h.
Defined functions:
As already mentioned, more than 20 functions are defined in this header. Below we explain each function in detail.
For the type conversion:
1. duplo atof(const char *s)
This function converts the stringSfor a floating point number of typeintestineand returns it. It is equivalent to strtod(s,(char**)NULL).
If a valid conversion cannot be performed, returns0,0.
You can refer to the code snippet below to understand its implementation.
#include <stdio.h>#include <stdlib.h>#include <string.h>int main() { float value; Zeichenstr[20]; strcpy(string, "12345678"); value = atof(str); printf("String = %s, Float-Wert = %f\n", string, value); strcpy(str, "opengenus.org"); value = atof(str); printf("String = %s, Float-Wert = %f\n", string, value); return(0);}
Compiling the previous program, we would obtain this result:
String = 12345678, Float-Wert = 12345678.000000 String = opengenus.org, Float-Wert = 0.000000
2. int atoi(const char *s)
This function converts a stringSfor an integer, that isAnd tand returns it. It is equivalent to (int)strtol(s,(char**)NULL, 10).
If a valid conversion cannot be performed for the specified string, a null value is returned.
You can refer to the following code to understand its implementation:
#include <stdio.h>#include <stdlib.h>#include <string.h>int main () { valor int; char cadenas[20]; strcpy(cadenas, "12345678"); valor = atoi(strs); printf("Cadena = %s, Int valor = %d\n", strs, valor); strcpy(str, "opengenus.org"); valor = atoi(strs); printf("Cadena = %s, Int valor = %d\n", strs, valor); retorno(0);}
Compiling the previous program, we would obtain this result:
String = 12345678, Int Value = 12345678 String = opengenus.org, Int Value = 0
3. langes atoll (const char*s);
This function converts a stringSto a long integer (data type: long) and returns it. It is equivalent to strtol(s,(char**)NULL, 10).
If a valid conversion cannot be performed for the specified string, a null value is returned.
You can refer to the following code to understand its implementation:
#include <stdio.h>#include <stdlib.h>#include <string.h>int main () { long val; Zeichenstr[20]; strcpy(cadena, "12345678"); val = atol(cadena); printf("String-Wert = %s, Long-Wert = %ld\n", str, val); strcpy(str, "opengenus.org"); val = atol(cadena); printf("String-Wert = %s, Long-Wert = %ld\n", str, val); retorno(0);}
Compiling the previous program, we would obtain this result:
String Value = 12345678, Long Value = 12345678 String Value = opengenus.org, Long Value = 0
4. Doppelstrtod (const char *s, char **endp)
The functionstrtodconvert the prefixSforintestine, ignoring leading spaces. Stores a pointer to each suffix that has not been converted to *.endpunless it isNULL.
When the response overflowsHUGE_VALUEis returned with the corresponding sign. If the answer was insufficient,nullreturned In both cases, errno is defined asRANGE.
You can refer to the following code to understand its implementation:
#include <stdio.h>#include <stdlib.h>int main () { char str[30] = "21.32322 This is the text"; character *ptr; double ret; ret = strtod(str, &ptr); printf("The number(double) is %lf\n", ret); printf("The part of the string is |%s|", ptr); return(0);}
Compiling the previous program, we would obtain this result:
The (double) number is 21.323220. Part of the string is | This is the text|
You may notice that the whitespace between the number and the text is also included in the ptr string. Also note the extra zero at the end of the number, since the data type is double.
5. larga strtol(const char *s, char **endp, int base)
The functionis loyalConvert string prefixStoo long, ignoring leading spaces. Stores a pointer to each suffix that has not been converted toendpunless endp isNULL.
If the base is between 2 and 36, the conversion assumes that the input is written in that base. If the base is zero, the base is 8, 10, or 16. The leading 0 implies octal, and the leading 0x or 0X implies hexadecimal. The letters in both cases represent digits from 10 to base 1. A leading 0x or 0X is allowed in base 16.
If you don't understand the meaning of the above, just ignore it. You probably only need base 10.
If the response overflows, LONG_MAX or LONG_MIN is returned, depending on the sign of the result, and errno is set to ERANGE.
You can refer to the following code to understand its implementation.
#include <stdio.h>#include <stdlib.h>int main () { char str[30] = "2020200 This is the text"; character *ptr; long rest; ret = strtol(str, ptr, 10); printf("The number (long integer) is %ld\n", ret); printf("The part of the string is |%s|", ptr); return(0);}
Compiling the previous program, we would obtain this result:
The number (long integer) is 2020200. Part of the string is | This is the text|
6. strtoul largo sin firmar (const char *s, char **endp, int base)
The functionSTRTis the same asis loyalexcept that the result islong unsignedand the error value isHEAD_MAX.
#include <stdio.h>#include <stdlib.h>int main () { char str[30] = "2030300 This is the body part"; character *ptr; unsigned long ret; ret = strtoul(str, ptr, 10); printf("The number (unsigned long integer) is %lu\n", ret); printf("The part of the string is |%s|", ptr); return(0);}
Compiling the previous program, we would obtain this result:
The number (unsigned long integer) is 2030300. Part of the string is | This is the body|
To generate pseudorandom sequences:
1. inner edge (leather)
The functionRandreturns a pseudorandom in theRange from 0 to RAND_MAX, that is at least32767.
PD:Never use rand() for security reasons.
#include <time.h>#include <stdlib.h>#include <stdio.h>int main(){srand(time(NULL)); // Initialization, only needs to be called once // See the next topic to understand the function above int r = rand(); // Returns a pseudorandom number between 0 and RAND_MAX printf("Random number is: %d", r);}
Compiling the previous program, we would obtain this result:
The random number is: 16426
2. void srand (int-Seed sin firmar)
The functionArenaEUTogetheras the seed of a new sequence of pseudorandom numbers. The initial value is 1.
The following code shows the use of the srand function:
#include <stdio.h>#include <stdlib.h>#include <time.h>int main () { int i, n; time_t t; n=5; /* initialize the random number generator */ srand((unsigned) time(&t)); /* Print 5 random numbers from 0 to 50 */ for( i = 0 ; i < n ; i++ ) { printf("%d\n", rand() % 50); } return(0);}
The output of the above code is:
3845292947
For memory allocation and release:
1. void *calloc(size_t nobj, size_t size)
The functioncallreturns a pointer to a space in an array ofnobjobjects, each of sizeSize, oNULLif the order cannot be fulfilled. The space is initialized to zero bytes. For integers, the initial value is set to 0.
The following code shows how the above function works:
#include <stdio.h> #include <stdlib.h> int main () { int i, n; int*a; printf("Number of elements to insert:"); scan("%d",&n); a = (int*)calloc(n, sizeof(int)); printf("Enter %d numbers:\n",n); for( i=0 ; i < n ; i++ ) { scanf("%d",&a[i]); } printf("The numbers entered are: "); for( i=0 ; i < n ; i++ ) { printf("%d ",a[i]); } free( a );//This is a very good practice. Explained below. return(0);}
The result we get when we run the above code is:
Number of items to enter: 3 Enter 3 numbers: 122334 The numbers entered are: 12 23 34
2. empty malloc(size_t size)
The functionmallocreturns a pointer to a location for an object of sizeSize, oNULLif the order cannot be fulfilled. The space is not initialized.
If you try to access the values, you may get an error or a garbage value.
#include <stdio.h> #include <stdlib.h> int main() { int* ptr; intn, I; n=5; //Number of articles printf("Enter the number of articles: %d\n", n); ptr = (int*)malloc(n * size(int)); if (ptr == NULL) { printf("Unallocated memory.\n"); //Not enough space.exit(0); } else { printf("Successfully allocated memory with malloc.\n");for (i = 0; i < n; ++i) { ptr[i] = i + 1; }printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } } returns 0; }
The output of the above program would be:
Enter the number of items: 5 Memory successfully allocated with malloc. The elements of the matrix are: 1, 2, 3, 4, 5,
3. void * realloc (void * p, size_t size )
The functionReallokchanges the size of the object pointed to by p toSize. The content remains unchanged at the minimum of the old and new sizes. If the new size is larger, the new space will not be initialized. realloc returns a pointer to the new location, or NULL if the request is not granted, in which case ***p** remains unchanged.
Please refer to the following code to understand its implementation:
#include <stdio.h> #include <stdlib.h> int main() { int* ptr; intn, I; n=5; printf("Enter the number of elements: %d\n", n); ptr = (int*)calloc(n, sizeof(int)); if (ptr == NULL) { printf("Unallocated memory.\n"); output(0); } else { printf("Successfully allocated memory with calloc.\n"); for (i = 0; i < n; ++i) { ptr[i] = i + 1; } printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } n = 10; printf("\n\nEnter the new size of the array: %d\n", n); ptr = realloc(ptr, n * sizeof(int)); printf("Memory successfully reallocated with realloc.\n"); for (i = 5; i < n; ++i) { ptr[i] = i + 1; } printf("The elements of the array are: "); for (i = 0; i < n; ++i) { printf("%d, ", ptr[i]); } free(ptr); } returns 0; }
The output for the above code is:
Enter the number of items: 5 Memory allocated successfully with calloc. The elements of the array are: 1, 2, 3, 4, 5. Enter the new size of the array: 10 Memory was successfully reallocated with realloc. The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
4. invalid book (empty *p)
The functionBuch expelthe space pointedPAG. Does nothing if p isNULL. p must be a pointer to memory previously allocated by calloc, malloc, or realloc.
Please refer to the following code to understand its implementation:
#include <stdio.h> #include <stdlib.h> int main() { int *ptr; intn, I; printf("Enter the number of elements: %d\n", n); ptr = (int*)malloc(n * size(int)); if (ptr == NULL) { printf("Unallocated memory.\n"); output(0); // Explained below. } else { // memory allocated successfully printf("Memory allocated successfully with malloc.\n"); // Free memory free(ptr); printf("Malloc memory released successfully.\n"); } returns 0; }
The output of the following code is:
Enter number of items: 5 Memory successfully allocated with malloc. Malloc memory released successfully.
For process control:
1. cancel null (empty)
The functioninterruptdoes the programterminate abnormally, as if throughincrease (SIGABRT).
#include <stdio.h>#include <stdlib.h>int main () { FILE *fp; printf("Open File1.txt\n"); fp = fopen("file1.txt","r"); if(fp == NULL) { printf("Abort program\n"); interrupt(); } printf("Nofile.txt\n will be closed"); fclose(fp); return(0);}
if the fileFechai1.txtis not found, then the output would be:
Go to open file1.txt Go to cancel program Canceled (core dump)
2nd zero output (int state)
The functionsalidacauses the program to exit normally.Salidathe functions are calledreverse orderlog releases open files, closes open streams, and returns control to the environment. However, the way the status is returned is implementation dependent.0 is considered a successful completion.
#include <stdio.h>#include <stdlib.h>int main () { printf("program start....\n"); printf("Exit program....\n"); output(0); //The following code will not be executed. printf("End of program....\n"); return(0);}
The output of the above code would be:
Start program....End program....
3. int atexit(void (*fcn)(void))
This is a commonly used function when you want a function to be executed before the program ends.
Salidaregister functionfncbe called when the program exits normally. Returns non-zero if registration fails.
See the following code for more information:
#include <stdio.h>#include <stdlib.h>void fcn () { printf("This is fcn...\n");}int main () { /* Register the termination function */ atexit( fcn ) ; printf("Starting main program...\n"); printf("Ending main program...\n"); return(0);}
The output of the following code would be:
Start main program... Exit main program... This is fcn...
4. Sistema int (const char *s)
The functionSystemrope passSFor himSurroundingsfor execution. If s is NULL. The system returns a non-zero value if a command processor is present. If s is not NULL, the return value is implementation dependent.
**PS:**This is implementation dependent.
Consider the following code:
#include <stdio.h>#include <string.h>int main () { char command[50]; strcpy(command, "dir"); system (command); return(0);}
The output I get when I run this on my Linux machine is:
You can see it in the commanddirectoryand running the program performs the same task. This is because the "dir" command is stored in the stringdomainin the above code.
5. char *getenv(const char *nombre)
Tenvreturns the environment string associated with the name, or NULL if no string is present. The details depend on the implementation.
The following program shows the use of theTenvFunction.
#include <stdio.h>#include <stdlib.h>int main () { printf("PATH: %s\n", getenv("PATH")); printf("HOME: %s\n", getenv("HOME")); printf("ROOT: %s\n", getenv("ROOT")); return(0);}
The output of the program on my (Linux based) machine is:
CAMINHO: home/vishnu/miniconda3/condabin:/home/vishnu/.nvm/versions/node/v11.0.0/bin:/home/vishnu/.local/bin:/usr/local/sbin:/usr/local/ bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/binHOME : /home/vishnuROOT : (nulo)
Sorting and search algorithms:
1. void *bsearch(const void *key, const void *base, size_t n, size_t size, int(*cmp)(const void *keyval, cont void *datum))
look forinvestigabase[0]...[n-1]for a matching item *Gusto. The cmp function should return negative if its first argument (the search key) is less than its second, zero if it is equal, and positive if it is greater. The elements at the base of the array must be in ascending order.look forreturns a pointer to a matching element, orNULLif none exist.
The following program can help you understand:
#include <stdio.h>#include <stdlib.h>int cmpfunc(const void * a, const void * b) { return ( *(int*)a - *(int*)b );}int valores[] = { 5, 20, 29, 32, 63 };int principal () {int *elemento; chave int = 29; /* usando bsearch() gegen Valor 29 no array */ item = (int*) bsearch (&chave, valores, 5, sizeof (int), cmpfunc); if( item != NULL ) { printf("Item encontrado = %d\n", *item); } else { printf("Item = %d não pôde ser encontrado\n", *item); } retorno(0);}
The output of the following program is:
Article found = 29
2. void qsort(void *base, size_t n, size_t size, int (*cmp)(const void *, const void *))
ordersorts an array in ascending orderBase[0]...Base[n-1]of size objectsSize. The cmp compare function is like in bsearch.
The following code may help you understand:
#include <stdio.h>#include <stdlib.h>int valores[] = { 88, 56, 100, 2, 25 };int cmpfunc (const void * a, const void * b) { return ( *(int *)a - *(int*)b );}int main() { int n; printf("Antes de ordenar una lista é:\n"); for(n = 0; n < 5; n++) { printf("%d", Werte[n]); } qsort(valores, 5, sizeof(int), cmpfunc); printf("\nDepois de ordenar una lista fica: \n"); for(n = 0; n < 5; n++) { printf("%d", Werte[n]); } azul (0);
The output of the above code is:
Before ordering, the list is: 88 56 100 2 25 After ordering, the list is: 2 25 56 88 100
Mathematics:
1. int abs(int n)
Abdomenreturns the absolute value of itsAnd tcalle
Here is an example code:
#include <stdio.h>#include <stdlib.h>int main() { int a, b; a = abs(50); printf("value of a = %d\n", a); b = abs(-1); printf("value of b = %d\n", b); return(0);}
The output of the code is:
value of a = 50 value of b = 1
2. lange Labore (n lang)
Work hardreturns the absolute value of itslanguagecalle
Here is an example code:
#include <stdio.h>#include <stdlib.h>int main () { long int a,b; a = Labore (65987L); printf("Wert von a = %ld\n", a); b = Labore (-1005090L); printf("Wert von b = %ld\n", b); retorno(0);}
The output of the above code is:
Value of a = 65987 Value of b = 1005090
3. div_t div(int number, int denominator)
divisionCalculate the quotient and the remaindernumber. The results are stored in int elementsCitationmiResta structure of type div_t.
The following code shows a clear example:
#include <stdio.h>#include <stdlib.h>int main() { div_t output; output = div(27, 4); printf("Proportion of (27/4) = %d\n", output.quot); printf("Remaining part of (4/27) = %d\n", output.rem); output = div(27, 3); printf("Proportion of (27/3) = %d\n", output.quot); printf("Remaining part of (3/27) = %d\n", output.rem); return(0);}
The output for the above code is:
Quotient of (27/4) = 6 Remaining part of (27/4) = 3 Quotient of (27/3) = 9 Remaining part of (27/3) = 0
4. ldiv_t ldiv(long number, long denominator)
divisionCalculate the quotient and the remaindernumber. Results are stored in long membersCitationmiResta structure of type ldiv_t.
An example of this is shown below:
#include <stdio.h>#include <stdlib.h>int main() { output ldiv_t; output = ldiv(100000L, 30000L); printf("Quote = %ld\n", output.quot); printf("Remainder = %ld\n", output.rem); return(0);}
The output of the above would be:
Quotient = 3 Remainder = 10000
Data types included:
1. size_t
This is the unsigned integer type and the result ofsize ofKeyword. We have already seen it in our functions.
2. wchar_t
This is an integer type of size aLargocharacter constants.
3. div_t
This is the structure returned bydivisionFunction.
4. ldiv_t
This is the structure returned byldivFunction.
macros included:
1. NULL
This macro is the value of anull pointer constant.
2. EXIT_FAILURE
That is the valueoutput functionReturns in case ofFail.
3. EXIT_SUCCESS
That is the valueoutput functionReturns in case ofSuccess.
4. RAND_MAX
This macro is the maximum value returned byrand function.
5. MB_CUR_MAX
This macro is themaximum number of bytesin a multibyte character set that cannot be greater thanMB_LEN_MAX.
Ask:
Which of the following functions has an unsigned long int return data type?
STRT
is loyal
strtod
Atoll
Among them, only strtoul is the function that returns an unsigned long int.
With this article inOpenGenus, you should get the full idea of using stdlib.h in C. Have fun.