-2

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));
          }
        }

1 Answers1

0

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

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63