简体   繁体   中英

Dynamic char array, size is fixed?

I am trying to create a char array dynamically. However, do not matter which number I put as the desired value of the size array it just keep using 4 has the size. If I place 3,2 or even 8, 10 it does not change...

Part where I initialize it...

char *x;

x = (char *)calloc(10, sizeof(char));

if(x == NULL )
{
    return;
}

cout <<"Size_Vector = "<<sizeof(x)<<endl; //Keep making the size of the array 4..no matter what

x is a pointer of type char * . sizeof(x) returns the size of the pointer instead of the array size.

Generally, there is no way to know the array size from a pointer type even if it's pointing to an array, because of array decaying .

char *x = malloc(sizeof(char)*10);
// This will give you 4
printf ("%d\n", sizeof(x));

But you can get the size of an array type.

char x[10];
// This will give you 10
printf ("%d\n", sizeof(x));

sizeof(x) returns the size of the pointer not the allocated memory or the size of array.

It always returns 4 size of an pointer on your envrionment is 4 and it will be the same for all.

You will have to keep track of how much memory you allocated yourself & also ensure that you do not write beyond the bounds of that allocated memory.

The malloc call returns a void pointer and when you say sizeof(pointer) you ask for the size of the pointer and not the chunk of memory that you just declared.So it gives you 4/8/... bytes depending on the m/c you are using.

Try this out :

char *cptr;

int *iptr;

printf("size of integer pointer is : %d\n",sizeof(iptr));


printf("size of character pointer is : %d\n",sizeof(cptr));

Note : malloc points to the address of the first element of the chunk of memory(ie 10 * 1 = 10 bytes) that you have dynamically obtained by calling it.

This is a short piece of code i wrote for you in case you really want to find the size of the memory piece you reserved by calling calloc though its obvious that when you say 10 spaces of 1 byte each then you are going to get 10 bytes like the case here which says you want 10 * sizeof(char) :

#include<stdio.h>

#include<stdlib.h>

main(){

    char *ptr = NULL;

    int i = 0;

    int size = 0;

    int n = 0;

    printf("Enter the size of the dynamic array in bytes : ");

    scanf("%d",&n);

    ptr = (char*) calloc (n,sizeof(char));

    for(i=0;i<n;i++){

            size = size + sizeof(ptr[i]);

    }

    printf("Size is %d\n",size);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM