-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;
}
9
  • 5
    T is uninitialized when you are creating your pointer array strings Commented Mar 5, 2014 at 18:45
  • @Andreas got it, but the array is 0 length (T would be initialized to 0), right? Commented Mar 5, 2014 at 18:48
  • @Andreas T will be given by the user when program executes. Commented Mar 5, 2014 at 18:51
  • 1
    But then strings is already allocated. Read stackoverflow.com/questions/14049777/… Commented Mar 5, 2014 at 18:52
  • 4
    @JohnYost local variables cannot be counted on to be initialized implicitly, so no, T would not (reliably) be initialized to 0. Commented Mar 5, 2014 at 18:52

2 Answers 2

2

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

int T= 6; 
Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

but T value will be given by user when program executes.
@user1463736, yes, but then the array of pointers is already allocated in memory!
@smarinov ok got it now. Thanks everyone for the help !
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().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.