0

I am trying to store a given input number of sets of strings in a 3D character array, but couldn't. Is it even possible using char arrays or should i use any other concept like data structures......?

int main()
{
int i,j,T,N[10];
char word[10][10][10];
scanf("%d",&T);/* No of test cases*/      
for(i=0;i<T;i++)
{
    scanf("%d",&N[i]); /*No of strings*/
    for(j=0;j<N[i];j++)
        scanf("%s",word[i][j]); /* reading the strings*/
}
 return 0;
4
  • Please share some code with us. What have you tried? Commented Oct 26, 2018 at 8:36
  • 1
    Yes it is possible, if you couldn't then you did something wrong. What that was is impossible to say because you don't show your code. Commented Oct 26, 2018 at 8:40
  • Your code works fine, but you should include stdio.h. Commented Oct 26, 2018 at 8:54
  • Yes this code is technically correct. Are you inserting words longer than 9 characters? What is it that is not working? Commented Oct 26, 2018 at 9:00

1 Answer 1

1

First: a "3D character array" is better thought of as a "2D string matrix" in this case.

And yes, of course it's very possible.

There are some weaknesses with your code that might trip it up, hard to say since you don't show a full test case with the input data you provide.

  1. scanf() can fail, in which case you cannot rely on the variables having values
  2. scanf() with %s will stop on the first whitespace character, which might cause your scanning code to become very confused
  3. You don't limit the size of string you scan, but only provide 10 bytes of buffer space per string, so easy to get buffer overruns.

A better solution would be to check that the scanning succeeded, and make each string be on a line on its own, and read full lines using fgets() into an appropriately-sized buffer, then perhaps copy the part you want to keep into place in the matrix.

Sign up to request clarification or add additional context in comments.

Comments

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.