1

I'm trying to create a multidimensional array to keep strings in it, with a length of 5. However it seems to be problem when i try to print out a sinle element from the arrays.

In my printf("%s", a[0][0][5]) it should print out "hej0" in a char array last [5]stand for the amout of characters of the current element + '\o' And first and second [] stand for row and which element to target?

When i try to compile this code it will just crash.

int main() {

    char a[3][4][5] = {
        {"hej0", "hej1", "hej2", "hej3"} ,
        {"hej4", "hej5", "hej6", "hej7"} ,
        {"hej8", "hej9", "hej10", "hej11"}
        };

    printf("%s", a[0][0][5]);
    return 0;
}  
2
  • Problem sloved, well done Commented Sep 11, 2014 at 9:08
  • 4
    Note that some of your strings are too long for the array dimensions (your compiler should be warning you about this!) - you really need char a[3][4][6] since you have some 5 character strings which need 6 bytes including terminator. Commented Sep 11, 2014 at 9:08

3 Answers 3

4

If you do :

printf("%s", a[0][0][5]);

You are trying to access the 6th character of the string pointed by a[0][0], which is "hej0". It has 4 characters and the fifth is the NULL terminating byte \0 (so you are trying to read beyond the string).

To print "hej0":

printf("%s", a[0][0]);
Sign up to request clarification or add additional context in comments.

1 Comment

a[0][0][5] is the 6th character, which is the first after '\0'
3

First issue I have seen your code is that size of array should be a[3][4][6] not a[3][4][5]. Because your elements "hej10", "hej11" required 6 bytes instead of 5. Also to print any particular element just provide base address like:

printf("%s", a[0][0]);

Comments

3

First problem is, if you want to put a 5 char string into a char array, you need to make the array 6 chars big, as it is terminated by character '\0'.

Second problem is, a[0][0][5] is the sixth element of the third row, which does not exist.

Third problem would be, if you want to print the complete string you should not specify a char number for output. Try a[0][0] instead of a[0][0][5]

Here is a correction:

char a[3][4][6] = {
    { "hej0", "hej1", "hej2", "hej3" },
    { "hej4", "hej5", "hej6", "hej7" },
    { "hej8", "hej9", "hej10", "hej11"}
};

printf("%s", a[0][0]);

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.