dynamically initialize a 3D character array in c [duplicate] - c

This question already has answers here:
Correctly allocating multi-dimensional arrays
(2 answers)
Closed 4 years ago.
I am trying to initialize a 3D character array, but couldn't. when i execute the program crashes.
I need to store 'T' sets of 'N[i]' no.of words in the ***word.characters in each word are less than 20.
"The program executes when static initialized."
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
#include<math.h>
int main()
{
int i,j,k,T,sum=0;
printf("\nEnter the no of test cases");
scanf("%d",&T);
int *N;
N=(int*)malloc(T*sizeof(int));
int **t;
t=(int**)malloc(T*sizeof(int*));
for(i=0;i<T;i++)
{
t[T]=(int*)malloc(N[i]*sizeof(int));
}
char ***word;
word = (char ***)malloc(T*sizeof(char**));
for (i = 0; i< T; i++)
{
word[T] = (char **) malloc(N[i]*sizeof(char *));
for (j = 0; j < N[i]; j++) {
word[T][N[i]] = (char *)malloc(20*sizeof(char));
}
}

In this line:
t[T]=(int*)malloc(N[i]*sizeof(int));
N[i] is uninitialized.
The same apply 3 times here:
word[T] = (char **) malloc(N[i]*sizeof(char *));
for (j = 0; j < N[i]; j++) {
word[T][N[i]] = (char *)malloc(20*sizeof(char));
}
So after
N=(int*)malloc(T*sizeof(int));
you should add some initialization like:
for(i=0;i<T;i++)
{
N(i) = 10 + i; // or whatever dimension you need
}
BTW: You don't need all the casting of malloc

Related

C - writing and reading a dynamical array

I'm trying to create a 2D array for storing names (with max 50 characters each). I have written a code, but it isn't working properly, where's the problem? (I can do this with statics arrays, however at the beginning my program won't know how many names I will want to store in the array). Here's my code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n=5;
int size=51;
char *a_name=(char*)malloc(n*size*sizeof(char));
for(int i=0;i<n;i++){
scanf("%s",&a_name[i]);
}
for(int i=0;i<=n;i++){
printf("%s\n",a_name[i]);
}
return 0;
}
What you need is not an array of char but an array of char *.
Try this:
int n = 5, size = 51;
char **name_array = (char **)malloc(sizeof(char *) * n);
for (int i = 0; i < n; ++i) {
name_array[i] = (char *)malloc(sizeof(char) * size);
// You may initialize the array first.
scanf("%s\n", name_array[i]);
}
Remember to release the memory when you no longer need the names.

C: populate multiple dimension array [duplicate]

This question already has answers here:
Correctly allocating multi-dimensional arrays
(2 answers)
Closed 5 years ago.
I have several numbers that i want to insert into Matrix.
This is how i am get all my numbers one by one:
int i, n;
int ch;
int *arr;
int dimension;
int numbers = 0;
char str[512];
// User input.
fgets(str, sizeof str, stdin);
for (i = 0; i <= (strlen(str)); i++)
{
if (str[i] != '\0' && !isspace(str[i]))
{
int num = atoi(&str[i]);
numbers++;
if (i == 0)
{
dimension = num;
arr = allocatearraysize(dimension);
}
// Here i want to add the current number to my `Maxtix`.
}
}
free(arr);
int* allocatearraysize(int size)
{
return (int *)malloc(size * size * sizeof(int));
}
So i try:
arr[0][0] = num;
only for see if thats works but got an error:
expression must have pointer-to-object type
Edit
So if my input is 2 1 2 3 4:
the first number (2) means that my matrix should be 2x2 and i expected 4 numbers after this number (2).
In case the numbers of number not match the first number for example:
3 1 2 3 4
The first number here is 3 so after this number i excepted to 9 numbers so in this case i only want to print error message.
But any way i want to insert this numbers into my Matrix.
You can't access arrays with var[i][j] if it's not a 2-dimensional array.
A possible answer would be :
int i, j, n;
int ch;
int **arr;
int size;
int numbers = 0;
char str[512];
fgets(str, sizeof str, stdin);
size = atoi(&str[0]);
if(size > 1) {
arr = (int**) malloc(size * sizeof(int*))
for (i = 0; i < size; i++)
arr[i] = (int*) malloc(size * sizeof(int));
// Fill with arr[i][j]
free(arr);
}
else {
fprintf(stderr, "Size must be a valid number");
}

How can I free memory in a dynamically allocated array? [duplicate]

This question already has answers here:
2D array dynamic memory allocation crashes [duplicate]
(2 answers)
Closed 6 years ago.
I'm a newbie trying to learn how to make dynamics arrays in C. The code doesn't give me any errors when I build it using code:blocks, but when I run it crashes. I think the crash has to do with the way I'm freeing my memory, because the code is giving me the desired output before crashing.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, j;
int *p = (int *)malloc(sizeof(*p));
printf("Hello World! I have created a dynamic array of 20x30 integers! \n");
for (i = 0; i <= 19; i++)
{
p[i] = (int )malloc(sizeof(int*));
printf(" %2d ", i);
for (j = i + 1; j <= 29 + i; j++)
{
p[i] = 0;
printf("%2d", j);
}
printf("\n");
}
for (i = 0; i <= 19; i++);
{
free(p[i]);
}
free(p);
return 0;
}
Here's the problem.
First, your first malloc call allocates space for a 1-element array.
You'll want to change it from
int *p = (int *)malloc(sizeof(*p));
to
int *p = (int *)malloc(sizeof(int*) * 20);
And then your second malloc call is slightly incorrect as well.
p[i] = (int )malloc(sizeof(int*));
should be changed to
p[i] = (int *)malloc(sizeof(int));
You just put the asterisk in the wrong place.
Finally, you really only create a 20-element array. All you do in the inner for loop is assign each cell in the array the value 0 times. If you want to make a 20x30 array, you can always take the easy route and create a 1D array and use some math (which is ultimately what the compiler does with non-dynamic 2D arrays anyway):
int main()
{
int *p = (int *)malloc(sizeof(int) * 600);
...
for (i = 0; i <= 19; i++)
{
printf(" %2d ", i);
for (j = 0; j <= 29; j++)
{
p[i * 30 + j] = 0; // It's i * 30, not i * 20 because you have to skip the space that the 'j' dimension takes up.
printf("%2d", j);
}
printf("\n");
}
free((void*)p); //I found the program crashes without the void* cast
}
I've tested this code and it runs.
Hope this helps.

How to allocate a 2D array of pointers to a struct [duplicate]

This question already has answers here:
How do I correctly set up, access, and free a multidimensional array in C?
(5 answers)
Closed 6 years ago.
This is were I got so far,but I don't know if it's right.
This function receives the dimensions of the 2D array (nxn),and allocates it.
flightInfo is the name of the struct.
Will this work?
thanks in advanced
after allocating the array(ignore the method ,since we are not allowed to use the method you proposed) I would like to initialize the struct (I built a function to do it but it didn't work),I tried to do it right after the allocation and kept getting the" Unhandled exception" warning, does it has to do
with the syntax, am I forgetting a '*'?
void flightMatrix()
{
FILE * fpf;
int checkScan,Origin,Dest;
float time,cost;
char flightName[3];
flightInfo *** matrix;
if(!(fpf=fopen("flights.txt","r")))exit(1);
while((checkScan=fscanf(fpf,"%*10c%3d%3d%3c%5f%7f%*",&Origin,&Dest,flightName,&time,&cost))!=EOF)
{
matrix=allocateMatrix(Dest);
matrix[Origin-1][Dest-1]->o=Origin;
}
}
flightInfo*** allocateMatrix(int n)
{ int i,j;
flightInfo*** matrix;
matrix=(flightInfo***)malloc(sizeof(flightInfo **)*n);
for(i=0;i<n;i++)
matrix[i]=(flightInfo **)malloc(sizeof(flightInfo*)*n);
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
matrix[i][j] = NULL;
}
return matrix;
}
[http://i.stack.imgur.com/MFC7V.png]
this is what happens when I try to initialize
Technically speaking, this won't create 2D array. The result will be array of pointers, where each one points to different array of pointers to a struct.
The difference is that, memory will be fragmented, so every element will point to some memory location, instead of single continuous memory block.
The common approach for this is to create flatten 2D array:
flightInfo** allocateMatrix(int n)
{
flightInfo** matrix = malloc(n*n * sizeof(*matrix));
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix[i*n + j] = NULL;
return matrix;
}
If you are forced to use two indices, then you could place matrix as function argument:
void allocateMatrix(int n, flightInfo* (**matrix)[n])
{
*matrix = malloc(n * sizeof(**matrix));
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
(*matrix)[i][j] = NULL;
}
The second asterisk is required, because pointers are passed by value, otherwise you would end up with modified local copy of the pointer, that does nothing to matrix from main function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct flightInfo {
char airport[30];
int altitude;
} flightInfo;
void allocateMatrix(int n, flightInfo* (**matrix)[n])
{
*matrix = malloc(n * sizeof(**matrix));
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
(*matrix)[i][j] = NULL;
}
int main()
{
int n = 10;
flightInfo* (*matrix)[n];
allocateMatrix(n, &matrix);
matrix[0][0] = malloc(sizeof(flightInfo));
strcpy(matrix[0][0]->airport, "Heathrow");
matrix[0][0]->altitude = 10000;
printf("%s, %d\n", matrix[0][0]->airport, matrix[0][0]->altitude);
}
The another way would be to encapsulate the array within a struct.

Pointer and struct array manipulation in C

#define MAX_KEYS 65
struct Key {
int id;
char cryptkeys[MAX_KEYS];
};
int main(int argc, char ** argv) {
int MAX_LINE = 69;
struct Key *table[3];
struct Key *(*p)[] = &table;
//allocating space for the pointers in array
for(int i = 0; i < 4; i++) {
table[i] = malloc(sizeof(struct Key));
}
//parsing the id and the keys
char id[3];
char key[65];
for(int i = 0; i < size-1; i++) {
struct Key *k = (struct Key*)malloc(sizeof(struct Key));
string = a[i];
strncpy(id, string, 3);
id[3] = '\0';
k->id = atoi(id);
for(int j = 4; j < strlen(string); j++) {
key[j-4] = string[j];
}
strcpy(k->cryptkeys, key);
table[i] = k;
printf("%s", table[i]->cryptkeys); //this will print
}
for(int i = 0; i < sizeof(table) -1; i++) {
printf("%d", table[i]->id); //seg fault here, what is the difference from above?
printf(" ");
printf("%s", table[i]->cryptkeys);
}
return 0;
}
Hi everyone, I had a question about manipulating pointers in C. I have declared an array of pointers that will be filled with structs that I have created. Each struct accepts a int and string value that I read in from a file. My question is about editing the values inside of my array, specifically assigning new values and accessing the values already in there. I assign my values after parsing them from the file, but I get a segmentation fault when I try to print them out below. Why does my code keep segfault in my last loop, do I have to print out values in an array of pointers differently than I normally would? Thank you!
sizeof(table) is not 3. It's actually 24 which is 3*8 (number of array elements*size of an address). You get segmentation fault because you try to access table[3] (and so on) which is not allocated.

Resources