Hi Guys,

I am trying to create array of 9 strings dynamically in below code snippet but while accessing elements i am getting all the elements null instead of accessing actual element of array.Please suggest.

#include<stdlib.h>
#include <stdio.h>
#include <string.h>

int main()
{

char **arrayofstr;
char str[250]={0,};

int i;
for (i=0;i<9;i++)
{
arrayofstr = malloc(9 * sizeof (char*));
printf("enter the string");
fgets(str,25, stdin);

// In the second level
arrayofstr[i] = malloc(strlen(str) + 1);
strcpy(arrayofstr[i],str);
printf("%s",arrayofstr[i]);
}
int i;
for(i=0;i<9;i++)
{
  printf("%s",arrayofstr[i]); 
}

}

arrayofstr = malloc(9 * sizeof (char*)) is misplaced. Move it outside of your first loop.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.