Stdlib h что это

Stdlib.h

stdlib.h

Содержание

Member functions

Члены stdlib.h можно разделить на следующие категории: преобразования типов, управление памятью, контроль процесса, сортировка и поиск, математика.

ИмяОписание
Преобразование типов
atofстрока в число двойной точности (НЕ float)
atoiстрока в целое число
atolстрока в длинное целое число
strtodстрока в число двойной точности (double)
strtolстрока в длинное целое число
strtoulстрока в беззнаковое длинное целое число (unsigned long int)
Генерация псевдослучайных последовательностей
randгенерирует псевдослучайное значение
srandустанавливает начальное значение генератора псевдослучайных чисел
Выделение и освобождение памяти
malloc
calloc
realloc
выделяет память из кучи
freeосвобождает память обратно в кучу
Контроль процесса выполнения программы
abortнекорректное завершение выполнения
atexitрегистрирует обратный вызов функции для выхода из программы
exitзавершает выполнение программы
getenvизвлекает переменные окружения
systemвыполняет внешнюю команду
Сортировка и поиск
bsearchдвоичный поиск в массиве
qsortсортировка массива
Математика
abs
labs
абсолютная величина
div
ldiv
деление целых чисел
Многобайтовые операции/ широкие символы
mblenразмер многобайтовых символов [1]
mbtowc, wctomb, mbstowcs, wcstombsпреобразование многобайтовых и широких символов [2]

Члены-константы

Заголовочные файлы stdlib.h и stddef.h определяют макрос NULL, который порождает константный нуль-указатель, и представляет собой значение указателя, гарантирующего корректность указателя, не указывающего на действительный (корректный) адрес в памяти.

Варианты

NULL может быть определен как константное выражение, равное целому нулевому числу (нулю), длинному целому нулю, или нуль приводится к указателю типа void *:

Несмотря на то, что константа нуль-указателя всегда представляется в Си символьной константой 0 или 0, приведенным к void-указателю, реальное битовое представление подобного указателя зависит от системы и может содержать однобитовые значения.

Типы членов-данных

size_t

Настоящий тип size_t платформо-независим; распространенной ошибкой является подразумевание size_t как беззнаковое целое ( unsigned int ), что может привести к ошибкам программирования, [4] причем в первую очередь это касается 64-битных архитектур.

div_t, ldiv_t

Нестандартные функции

itoa — общая функция, входящая во множество реализаций stdlib.h, но стандарт не определяет функцию. Возможно, ее так часто включают в библиотеки благодаря ее описанию в книге Язык программирования Си. Аналогичного эффекта можно добиться при помощи функции sprintf, которая определена в стандарте.

См. также

Примечания

Ссылки

Полезное

Смотреть что такое «Stdlib.h» в других словарях:

Stdlib.h — is the header of the general purpose standard library of C programming language which includes functions involving memory allocation, process control, conversions and others. It is compatible with C++ and is known as cstdlib in C++. The name… … Wikipedia

Stdlib.h — Saltar a navegación, búsqueda stdlib.h (std lib: standar library o biblioteca estándar) es el archivo de cabecera de la biblioteca estándar de propósito general del lenguaje de programación C. Contiene los prototipos de funciones de C para… … Wikipedia Español

stdlib.h — (std lib: standard library o biblioteca estándar) es el archivo de cabecera de la biblioteca estándar de propósito general del lenguaje de programación C. Contiene los prototipos de funciones de C para gestión de memoria dinámica, control de… … Wikipedia Español

stdlib.h — Стандартная библиотека языка программирования С assert.h complex.h ctype.h errno.h fenv.h float.h inttypes.h iso646.h limits.h locale.h math.h setjmp.h signal.h stdarg.h stdbool.h stddef.h stdint.h … Википедия

Dao (programming language) — Infobox programming language name = Dao paradigm = Multi paradigm year = 2006 designer = Limin Fu latest release version = dao 1.0 preview latest release date = 2008 04 25 typing = statically typed or dynamically typed influenced by = C++, Lua,… … Wikipedia

Strtod — is a C language function that converts an ASCII string to a double precision value. It is utilized via the following sequence:double strtod(const char *restrict, char **restrict); [OpenGroup Technical Standards Documentation] Strtod is included… … Wikipedia

strtod — (сокр. от string to double, «строку в число двойной точности») функция языка Си, конвертирующая символ строки в число с плавающей запятой двойной точности. Определение функции имеет вид: double strtod ( const char * str, char ** endptr… … Википедия

Memory leak — A memory leak, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it back to the operating system. In object oriented programming, a memory leak happens when an object is… … Wikipedia

Источник

stdlib.h

Содержание

Функции

ИмяОписание
Преобразование типов
atofстрока в число двойной точности (double; НЕ float)
atoiстрока в целое число (integer)
atolстрока в длинное целое число (long integer)
atollстрока в длинное целое число (long long integer)
strtodстрока в число двойной точности (double)
strtofстрока в число одиночной точности (float)
strtolстрока в длинное целое число (long integer)
strtoldстрока в длинное двойной точности (long double)
strtollстрока в длинное целое число (long long integer)
strtoulстрока в беззнаковое длинное целое число (unsigned long integer)
strtoullстрока в беззнаковое длинное целое число (unsigned long long integer)
Генерация псевдослучайных последовательностей
randгенерирует псевдослучайное значение
srandустанавливает начальное значение генератора псевдослучайных чисел
Выделение и освобождение памяти
malloc
calloc
realloc
выделяет память из кучи
freeосвобождает память обратно в кучу
Контроль процесса выполнения программы
abortнекорректное завершение выполнения
atexitрегистрирует обратный вызов функции для выхода из программы
exitзавершает выполнение программы
getenvизвлекает переменные окружения
systemвыполняет внешнюю команду
Сортировка и поиск
bsearchдвоичный поиск в массиве
qsortсортировка массива
Математика
abs
labs
абсолютная величина
div
ldiv
деление целых чисел
Многобайтовые операции/ широкие символы
mblenразмер многобайтовых символов [1]
mbtowc, wctomb, mbstowcs, wcstombsпреобразование многобайтовых и широких символов [1]

Заголовочные файлы stdlib.h и stddef.h определяют макрос NULL, являющийся константным нуль-указателем, который гарантированно указывает на некорректный адрес памяти.

Варианты

NULL может быть определен как константное выражение, равное целому нулевому числу (нулю), длинному целому нулю, или нуль приводится к указателю типа void *:

Несмотря на то, что константа нуль-указателя всегда представляется в Си символьной константой 0 или 0, привёденным к void-указателю, реальное битовое представление подобного указателя зависит от системы и может содержать однобитовые значения.

size_t

Настоящий тип size_t платформо-независим; распространенной ошибкой является подразумевать под size_t беззнаковое целое ( unsigned int ), что может привести к ошибкам программирования, [3] причём в первую очередь это касается 64-битных архитектур.

div_t, ldiv_t

Нестандартные функции

itoa — общая функция, входящая во множество реализаций stdlib.h, но не определяемая стандартом. Возможно, её так часто включают в библиотеки благодаря её описанию в книге «Язык программирования Си». Аналогичного эффекта можно добиться при помощи функции sprintf, которая определена в стандарте.

См. также

Примечания

Ссылки

Полезное

Смотреть что такое «stdlib.h» в других словарях:

Stdlib.h — заголовок (заголовочный файл) стандартной библиотеки общего назначения языка Си, который содержит в себе функции, занимающиеся выделением памяти, контроль процесса выполнения программы, преобразования типов и другие. Заголовок вполне совместим с… … Википедия

Stdlib.h — is the header of the general purpose standard library of C programming language which includes functions involving memory allocation, process control, conversions and others. It is compatible with C++ and is known as cstdlib in C++. The name… … Wikipedia

Stdlib.h — Saltar a navegación, búsqueda stdlib.h (std lib: standar library o biblioteca estándar) es el archivo de cabecera de la biblioteca estándar de propósito general del lenguaje de programación C. Contiene los prototipos de funciones de C para… … Wikipedia Español

stdlib.h — (std lib: standard library o biblioteca estándar) es el archivo de cabecera de la biblioteca estándar de propósito general del lenguaje de programación C. Contiene los prototipos de funciones de C para gestión de memoria dinámica, control de… … Wikipedia Español

Dao (programming language) — Infobox programming language name = Dao paradigm = Multi paradigm year = 2006 designer = Limin Fu latest release version = dao 1.0 preview latest release date = 2008 04 25 typing = statically typed or dynamically typed influenced by = C++, Lua,… … Wikipedia

Strtod — is a C language function that converts an ASCII string to a double precision value. It is utilized via the following sequence:double strtod(const char *restrict, char **restrict); [OpenGroup Technical Standards Documentation] Strtod is included… … Wikipedia

strtod — (сокр. от string to double, «строку в число двойной точности») функция языка Си, конвертирующая символ строки в число с плавающей запятой двойной точности. Определение функции имеет вид: double strtod ( const char * str, char ** endptr… … Википедия

Memory leak — A memory leak, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it back to the operating system. In object oriented programming, a memory leak happens when an object is… … Wikipedia

Источник

stdlib.h

Содержание

Функции

Заголовочные файлы stdlib.h и stddef.h определяют макрос NULL, являющийся константным нуль-указателем, который гарантированно указывает на некорректный адрес памяти.

Варианты

NULL может быть определен как константное выражение, равное целому нулевому числу (нулю), длинному целому нулю, или нуль приводится к указателю типа void *:

Несмотря на то, что константа нуль-указателя всегда представляется в Си символьной константой 0 или 0, привёденным к void-указателю, реальное битовое представление подобного указателя зависит от системы и может содержать однобитовые значения.

size_t

Настоящий тип size_t платформо-независим; распространенной ошибкой является подразумевать под size_t беззнаковое целое ( unsigned int ), что может привести к ошибкам программирования, [3] причём в первую очередь это касается 64-битных архитектур.

div_t, ldiv_t

Нестандартные функции

itoa — общая функция, входящая во множество реализаций stdlib.h, но не определяемая стандартом. Возможно, её так часто включают в библиотеки благодаря её описанию в книге «Язык программирования Си». Аналогичного эффекта можно добиться при помощи функции sprintf, которая определена в стандарте.

См. также

Напишите отзыв о статье «Stdlib.h»

Примечания

Ссылки

Отрывок, характеризующий Stdlib.h

Если допустить, как то делают историки, что великие люди ведут человечество к достижению известных целей, состоящих или в величии России или Франции, или в равновесии Европы, или в разнесении идей революции, или в общем прогрессе, или в чем бы то ни было, то невозможно объяснить явлений истории без понятий о случае и о гении.
Если цель европейских войн начала нынешнего столетия состояла в величии России, то эта цель могла быть достигнута без всех предшествовавших войн и без нашествия. Если цель – величие Франции, то эта цель могла быть достигнута и без революции, и без империи. Если цель – распространение идей, то книгопечатание исполнило бы это гораздо лучше, чем солдаты. Если цель – прогресс цивилизации, то весьма легко предположить, что, кроме истребления людей и их богатств, есть другие более целесообразные пути для распространения цивилизации.
Почему же это случилось так, а не иначе?
Потому что это так случилось. «Случай сделал положение; гений воспользовался им», – говорит история.
Но что такое случай? Что такое гений?
Слова случай и гений не обозначают ничего действительно существующего и потому не могут быть определены. Слова эти только обозначают известную степень понимания явлений. Я не знаю, почему происходит такое то явление; думаю, что не могу знать; потому не хочу знать и говорю: случай. Я вижу силу, производящую несоразмерное с общечеловеческими свойствами действие; не понимаю, почему это происходит, и говорю: гений.
Для стада баранов тот баран, который каждый вечер отгоняется овчаром в особый денник к корму и становится вдвое толще других, должен казаться гением. И то обстоятельство, что каждый вечер именно этот самый баран попадает не в общую овчарню, а в особый денник к овсу, и что этот, именно этот самый баран, облитый жиром, убивается на мясо, должно представляться поразительным соединением гениальности с целым рядом необычайных случайностей.
Но баранам стоит только перестать думать, что все, что делается с ними, происходит только для достижения их бараньих целей; стоит допустить, что происходящие с ними события могут иметь и непонятные для них цели, – и они тотчас же увидят единство, последовательность в том, что происходит с откармливаемым бараном. Ежели они и не будут знать, для какой цели он откармливался, то, по крайней мере, они будут знать, что все случившееся с бараном случилось не нечаянно, и им уже не будет нужды в понятии ни о случае, ни о гении.
Только отрешившись от знаний близкой, понятной цели и признав, что конечная цель нам недоступна, мы увидим последовательность и целесообразность в жизни исторических лиц; нам откроется причина того несоразмерного с общечеловеческими свойствами действия, которое они производят, и не нужны будут нам слова случай и гений.
Стоит только признать, что цель волнений европейских народов нам неизвестна, а известны только факты, состоящие в убийствах, сначала во Франции, потом в Италии, в Африке, в Пруссии, в Австрии, в Испании, в России, и что движения с запада на восток и с востока на запад составляют сущность и цель этих событий, и нам не только не нужно будет видеть исключительность и гениальность в характерах Наполеона и Александра, но нельзя будет представить себе эти лица иначе, как такими же людьми, как и все остальные; и не только не нужно будет объяснять случайностию тех мелких событий, которые сделали этих людей тем, чем они были, но будет ясно, что все эти мелкие события были необходимы.
Отрешившись от знания конечной цели, мы ясно поймем, что точно так же, как ни к одному растению нельзя придумать других, более соответственных ему, цвета и семени, чем те, которые оно производит, точно так же невозможно придумать других двух людей, со всем их прошедшим, которое соответствовало бы до такой степени, до таких мельчайших подробностей тому назначению, которое им предлежало исполнить.

Основной, существенный смысл европейских событий начала нынешнего столетия есть воинственное движение масс европейских народов с запада на восток и потом с востока на запад. Первым зачинщиком этого движения было движение с запада на восток. Для того чтобы народы запада могли совершить то воинственное движение до Москвы, которое они совершили, необходимо было: 1) чтобы они сложились в воинственную группу такой величины, которая была бы в состоянии вынести столкновение с воинственной группой востока; 2) чтобы они отрешились от всех установившихся преданий и привычек и 3) чтобы, совершая свое воинственное движение, они имели во главе своей человека, который, и для себя и для них, мог бы оправдывать имеющие совершиться обманы, грабежи и убийства, которые сопутствовали этому движению.
И начиная с французской революции разрушается старая, недостаточно великая группа; уничтожаются старые привычки и предания; вырабатываются, шаг за шагом, группа новых размеров, новые привычки и предания, и приготовляется тот человек, который должен стоять во главе будущего движения и нести на себе всю ответственность имеющего совершиться.
Человек без убеждений, без привычек, без преданий, без имени, даже не француз, самыми, кажется, странными случайностями продвигается между всеми волнующими Францию партиями и, не приставая ни к одной из них, выносится на заметное место.

Источник

Complete guide on stdlib.h in C

Stdlib h что это. Смотреть фото Stdlib h что это. Смотреть картинку Stdlib h что это. Картинка про Stdlib h что это. Фото Stdlib h что это

is the header for the General Purpose Standard Library of C programming language which declares a variety of utility functions for type conversions, memory allocation, process control and other similar tasks. It also has multiple data types and macros defined in the header.

To use this header in C, you have to type the following line at the top of your C program:

The #include specifies inclusion of a system header file named x/*y.
This header can also be used in C++ by using cstdlib.
In this page, we will be describing all the functions, data types and macros defined in stdlib.h.

The Functions defined:

As mentioned earlier, there are more than 20 functions defined in this header. Below we have explained each and every function in detail.

For Type conversion:

1. double atof(const char *s)

This function converts the string s to a floating-point number of type double and returns it. It is equivalent to strtod(s,(char**)NULL).
If no valid conversion can be made, it returns 0.0.

You can refer to the below code snippet to understand its implementation.

On compiling the above program, we would get this result:

2. int atoi(const char *s)

This function converts a string s to an integer i.e int and returns it. It is equivalent to (int)strtol(s,(char**)NULL, 10).
If no valid conversions can be made for the given string, it then returns zero.
You can refer to the below code to understand its implementation:

On compiling the above program, we would get this result:

3. long atol(const char *s)

This function converts a string s to an long integer (data type: long) and returns it. It is equivalent to strtol(s,(char**)NULL, 10).
If no valid conversions can be made for the given string, it then returns zero.
You can refer to the below code to understand its implementation:

On compiling the above program, we would get this result:

4. double strtod(const char *s, char **endp)

The function strtod converts the prefix of s to double, ignoring the leading whitespace. It stores a pointer to any unconverted suffix in *endp unless it is NULL.
If the answer would overflow, HUGE_VAL is returned with the proper sign. If the answer would underflow, zero is returned. In either case errno is set to ERANGE.
You can refer to the below code to understand its implementation:

On compiling the above program, we would get this result:

You can notice that the white space in between the number and the text is also included in the string ptr. Also note the extra zero at the end of the number, this is because the data type is a double.

5. long strtol(const char *s, char **endp, int base)

The function strtol converts the prefix of string s to long, ignoring leading whitespace. It stores a pointer to any unconverted suffix in endp unless endp is NULL.
If base is between 2 and 36, conversion is done assuming that the input is written in that base. If base is zero, the base is 8, 10, or 16. Leading 0 implies octal and leading 0x or 0X hexadecimal. Letters in either case represent digits from 10 to base-1. A leading 0x or 0X is permitted in base 16.
If you didn’t understand what the above meant, just ignore it. You would most likely be needing only base 10.
If the answer would overflow, LONG_MAX or LONG_MIN is returned, depending in the sign of the result, and errno is set to ERANGE.
You can refer to the below code to understand its implementation.

On compiling the above program, we would get this result:

6. unsigned long strtoul(const char *s, char **endp, int base)

The function strtoul is the same as strtol except that the result is unsigned long and the error value is ULONG_MAX.

On compiling the above program, we would get this result:

For Pseudo-random Sequence Generation:

1. int rand(void)

The function rand returns a pseudo-random in the range 0 to RAND_MAX, which is at least 32767.
PS: Never use rand() for security purposes.

On compiling the above program, we would get this result:

2. void srand(unsigned int seed)

The function srand uses seed as the seed for a new sequence of pseudo-random numbers. The initial seed is 1.
The folowing code shows the use of the srand function:

The output of the above code is:

For Memory Allocation And Deallocation:

1. void *calloc(size_t nobj, size_t size)

The function calloc returns a pointer to a space for an array of nobj objects, each of size size, or NULL if the request cannot be satisfied. The space is initialized to zero bytes. For integers, the initial value is set to 0.
The below code shows the working of the above function:

The output we get on running the above code is:

2. void *malloc(size_t size)

The function malloc returns a pointer to a space for an object of size size, or NULL if the request cannot be satisfied. The space is uninitialized.
If you try to access the values, you could either get an error or a garbage value.

The output of the above program would be:

3. void *realloc(void *p, size_t size)

The function realloc changes the size of the object pointed by p to size. The contents will be unchanged upto minimum of the old and new sizes. If the new size is larger, the new space is uninitialized. realloc returns a pointer to the new space, or NULL if the request connot be satisfied, in which case ***p **is unchanged.
Please refer to the below code to understand its implementation:

The output for the above code is:

4. void free(void *p)

The function free deallocates the space pointed by p. It does nothing if p is NULL. p must be a pointer to space previously allocated by calloc, malloc or realloc.
Please refer to the below code to understand its implementation:

The output of the following code is:

For Process Control:

1. void abort(void)

The function abort causes the program to terminate abnormally, as if by raise(SIGABRT).

If the file file1.txt is not found, then the output would be:

2. void exit(int status)

The function exit causes normal program termination. atexit functions are called in reverse order of registration, open files are flushed, open streams are closed, and control is returned to the environment. The way status is returned is implementation dependent, but 0 is taken as a successful termination.

The ouptput of the above code would be:

3. int atexit( void (*fcn)(void))

This is a very popularly used function used when you want some function to be executed before the program exits.
atexit registers the function fcn to be called when the program terminates normally. It returns non-zero if the registration cannot be made.
Please refer to the below code for more information:

The output of the following code would be:

4. int system(const char *s)

The function system passes the string s to the environment for execution. If s is NULL. system returns non-zero if there is a command processor. If s in not NULL, the return value is implementation-dependent.
**PS:**This is implementation dependent.
Consider the below code:

The output I get when I execute this on my linux machine is :
Stdlib h что это. Смотреть фото Stdlib h что это. Смотреть картинку Stdlib h что это. Картинка про Stdlib h что это. Фото Stdlib h что это
You can see that the command dir and executing the program do the same task. This is because the command «dir» is what is stored by the string command in the above code.

5. char *getenv(const char *name)

getenv returns the environment string associated with name, or NULL if no string exists. Details are implementation-dependent.
The below program shows use of the getenv function.

The Output of the program on my machine (linux based) is:

Sorting And Searching Algorithms:

1. void *bsearch(const void *key, const void *base, size_t n, size_t size, int(*cmp)(const void *keyval, cont void *datum))

bsearch searches base[0]. [n-1] for an item that matches *key. The function cmp must return negative if its first argument (the search key) is less than its second, zero if equal, and positive if greater. Items in the array base must be in ascending order. bsearch returns a pointer to a matching item, or NULL if none exists.
The below program could aid your understanding:

The output of the following program is:

2. void qsort(void *base, size_t n, size_t size, int (*cmp)(const void *, const void *))

qsort sorts into ascending order an array base[0]. base[n-1] of objects of size size. The comparision function cmp is as in bsearch.
The below code could aid your understanding:

The output of the above code is:

Mathematics:

1. int abs(int n)

abs returns the absolute value of its int argument.
Below is an example code:

The output of the code is :

2. long labs(long n)

labs returns the absolute value of its long argument.
Below is a sample code:

The output of the above code is:

3. div_t div(int num, int denom)

div computes the quotient and the remainder of num/denom. The results are stored int the int members quot and rem of a structure of type div_t.
The below code shows a clear example:

The output to the above code is :

4. ldiv_t ldiv(long num, long denom)

div computes the quotient and remainder of num/denom. the results are stored in the long members quot and rem of a structure of type ldiv_t.
An example for this is shown below:

The output for the above would be:

The Data Types Included:

1. size_t

This is the unsigned integer type and is the result of the sizeof keyword. We have already seen this up in our functions.

2. wchar_t

This is an integer type of the size of a wide character constant.

3. div_t

This is the structure that is returned by the div function.

4. ldiv_t

This is the structure that is returned by the ldiv function.

The Macros Included:

1. NULL

This macro is the value of a null pointer constant.

2. EXIT_FAILURE

This is the value the exit function returns in case of failure.

3. EXIT_SUCCESS

This is the value the exit function returns in case of success.

4. RAND_MAX

This macro is the maximum value that is returned by the rand function.

5. MB_CUR_MAX

This macro is the maximum number of bytes in a multi-byte character set which cannot be larger than MB_LEN_MAX.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *