-2

The following program works in gcc but on giving the value of T = 6, this program continues and does not end on asking for input strings. Any help guys if you recognise whats wrong with this program?

int main()
{ int T,i,j;
  char *strings[T];
  printf("Enter the Number of Strings to Reverse : \n");

  scanf("%d ",&T);

  for(i=0;i<T;i++)
   { strings[i] = (char *)malloc(100*sizeof(char));
     scanf("%s\n",strings[i]);
   }
  for(i=0;i<T;i++)
   {printf(" The String %d is : %s\n",i+1,strings[i]);
  }
return 0;
}

2 Answers2

2

T is not initialised (Remember in C++, local scope variables are not automatically initialised) :

int T= 6; 
Jeshen Appanna
  • 480
  • 4
  • 16
1

T is not initialized inside main() therefore has an undefined value.

char *strings[T] creates an array of char * pointers of an undefined length.

Fix this using:

int T=6;

Or, given T is in fact constant:

const int T=6

or perhaps better

#define T 6

Feel free to use a more mnemonic name than T.

abligh
  • 24,573
  • 4
  • 47
  • 84
  • but T value will be given by user when program executes. – user1463736 Mar 05 '14 at 19:20
  • @user1463736, yes, but then the array of pointers is **already allocated** in memory! – Stefan Marinov Mar 05 '14 at 19:21
  • @smarinov ok got it now. Thanks everyone for the help ! – user1463736 Mar 05 '14 at 19:25
  • 1
    You could move the declaration of `strings` after `T` has been read. However, you are relying on (I believe) a gnu extension for that to work. A more common way would be to dynamically allocate a data structure of size `T * sizeof (char *)` using `malloc()`. – abligh Mar 05 '14 at 19:27