What allocates char * do size memory?

char    *str;
str = malloc(sizeof(char) * 5);

This code allocates 5 consecutive memory slots of a variable strthat has a type char *.

char    *str;
str = malloc(sizeof(char *) * 5);

It is supposed to allocate 5 times more char array memory. But since the array from char has no size until we declare it, what does this operator actually do?

+4
source share
5 answers

Following code

char **str = malloc(sizeof(char *) * 5);

allocates memory for 5-consecutive type elements char *, that is: a pointer to char.

Then you can select N-consecutive type elements charand assign their addresses to these pointers:

for (int i = 0; i < 5; i++)
   str[i] = malloc(sizeof(char) * N));
+2
source

5 " " str, char *.

, . , , , 5 char s, malloc(). C sizeof(char) 1, 5 .

, C11, §7.22.3.4

malloc() , size .

, " " , ( "" ) .

char *, . , 5 * sizeof (char *), sizeof(char *) 4, 8 - .

, , void *.


, malloc(), , size malloc().

, , sizeof(int) === sizeof(float),

    int *intPtr = malloc(sizeof *fltPtr);   //int pointer
    float *fltPtr = malloc(sizeof *intPtr); // float pointer

, .

+6
char    *str;
str = malloc(sizeof(char *) * 5);

5 char (5 ). ,

+1

5 char, .

+1
// main.c

#include <stdio.h>
int main()
{
    printf("%u\n", sizeof(char *));
}

32- , 4. 64- 8. ( 64- , .)

, char *str = malloc(sizeof(char *) * 5); 20 40 , str. , c-type str, 19 39.


I am on 64-bit Ubuntu 14.04. In a 64-bit environment, you can test the above code example with the following compiler options.

$ gcc -m32 -o out32 main.c
$ ./out32
4
$ gcc -o out64 main.c
$ ./out64
8

If you receive an error message sys/cdefs.h: No such file or directory, install the following packages.

$ sudo apt install libx32gcc-4.8-dev
$ sudo apt install libc6-dev-i386

(The resulting package names from this article )

0
source

Source: https://habr.com/ru/post/1677916/


All Articles