how to dynamically allocate memory for every element in 2D array? For example, I have an address which consist of street name(1.column) and street number(2.column) eg St.Paul 87/45. And I need to dynamically allocate memory for them.
int main()
{
int c = 1, r = 1; //c-column, r-row
char st_name[] = "St.Paul";
char st_number[] = "87/45";
char *arr = (char *)malloc(c*r*sizeof(char));
c = 0;
r = 0;
*arr[r][c++] = (char *)malloc((strlen(st_name)) * sizeof(char));
*arr[r][c] = (char *)malloc((strlen(st_number)) * sizeof(char));
return 0;
}
Of course it´s not working.
Thanks.
What you need is a matrix, but each matrix item is a c-string so an array.
You can do it using 3 starts pointer, like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int c = 1, r = 1; //c-column, r-row
char st_name[] = "St.Paul";
char st_number[] = "87/45";
char ***arr = malloc(r*sizeof(char *));
c = 0;
r = 0;
if (arr != NULL)
{
arr[r] = malloc(c*sizeof(char *));
if (arr[r] != NULL)
{
arr[r][c] = malloc(strlen(st_name)+1);
if (arr[r][c] != NULL)
{
c++
arr[r][c] = malloc(strlen(st_number)+1);
if (arr[r][c] != NULL)
{
sprintf( arr[0][0], st_name);
sprintf( arr[0][1], st_number);
printf ("arr[0][0] = %s\n", arr[0][0]);
printf ("arr[0][1] = %s\n", arr[0][1]);
}
}
}
}
return 0;
}
Or you can do that using a struct that defines each item of your array, like
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct item
{
char *name;
char *number;
};
int main(void)
{
char st_name[] = "St.Paul";
char st_number[] = "87/45";
int r = 1;
struct item *arr = malloc(r*sizeof(struct item));
if (arr != NULL)
{
arr[0].name = malloc(strlen(st_name)+1);
arr[0].number = malloc(strlen(st_number)+1);
if ((arr[0].name != NULL) && (arr[0].number != NULL))
{
sprintf( arr[0].name, st_name);
sprintf( arr[0].number, st_number);
printf ("arr[0][0] = %s\n", arr[0].name);
printf ("arr[0][1] = %s\n", arr[0].number);
free(arr[0].name);
free(arr[0].number);
}
free(arr);
}
return 0;
}
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.