int main() {
char *p[] = {"hello", "goodbye"};
char **a;
a = malloc(4 * 8);
}
I want a to have double the slots of p. How would I successfully do that without manually putting in numbers. All IK is the size of p should be there and x 2 for the double. How would I get the 8?
I think what you are asking is how to figure out how many strings have been put in p
. To do this, you can count the number of elements in p
:
char *p[] = { "hello", "goodbye" };
printf("%zu\n", sizeof(p) / sizeof(*p));
sizeof(p)
is the total size of p
sizeof(*p)
is the size of a single element of p
so dividing them gives you the number of elements in p
To malloc()
a second array, twice as large :
int main() {
char *p[] = { "hello", "goodbye", "lala" };
size_t size = sizeof(p) / sizeof(*p);
char **a;
a = malloc(size * 2 * sizeof(*a));
}
Using the sizeof
operator which returns you the size in bytes that a type/variable needs.
In your case
int main() {
// because "hello" and "goodbye" are const char*
const char *p[] = {"hello", "goodbye"};
size_t len_p = sizeof p / sizeof p[0];
char **a;
a = malloc( 2 * len_p * sizeof *a );
...
free(a);
}
sizeof p / sizeof p[0];
returns you the number of elements in the p
array. sizeof p
returns you the total amount of bytes, sizeof p[0]
returns you the size of single element. Hence total size / size of element returns you the number of elements. But be aware that this method only works for arrays, not pointer. Consider this:
void add_one(int *ptr)
{
size_t len = sizeof ptr / sizeof ptr[0];
for(size_t i = 0; i < len; ++i)
ptr[i] += 1;
}
int main(void)
{
int arr[] = { 1,2 3 };
add_one(arr);
return 0;
}
is wrong, because ptr
is pointer, not an array, so sizeof ptr
returns you the size of a pointer, not the total amount of bytes needed by arr
. That's why when you write a function that takes a pointer where you pass an array, the function should also take the size of the array, otherwise the size cannot be calculated, for example:
void add_one(int *ptr, size_t len)
{
for(size_t i = 0; i < len; ++i)
ptr[i] += 1;
}
int main(void)
{
int arr[] = { 1,2 3 };
add_one(arr, sizeof arr / sizeof arr[0]);
return 0;
}
void allocarr(char** matrix, int bytes, int slots)
{
int i = 0;
while(i <= slots)
{
matrix[i] = (char*)calloc(1, bytes);
++i;
}
}
...
char** s = malloc(4*sizeof(char*);
s = allocarr(s, 512, 4);
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.