1

Trying to revise for a coding exam and I came across this slide. Can any of you help me to understand how to print the strings from a pointer to array? Here is the code sample:

#include <stdio.h>

int main(void)
{
    size_t i;
    const char *suit[4] = { "Hearts", "Diammonds", "Clubs", "Spades" };

    printf("The strings in array const char*suit[4] is:\n\n");


    for (i = 0; i < 5; i++)
    {
        printf("const char *suit[%u] is: %s\n", i, suit[i]);
    }
}

When I print, I get this output:

The strings in array const char*suit[4] is:

const char *suit[0] is: Hearts
const char *suit[1] is: Diammonds
const char *suit[2] is: Clubs
const char *suit[3] is: Spades

However, it came with this error as well. "Exception thrown at 0x7AAD170C (ucrtbased.dll) in Pointer Practice.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC."

Why is there an error? How do I print the same output, but without an error?

Thank you in advance guys!

5
  • 1
    As you can see in your output, the largest index is 3. Your loop is trying to access index 4 which does not exist. Why do you think that you need to do that? Commented Dec 8, 2020 at 6:06
  • I have no excuses. Commented Dec 8, 2020 at 6:08
  • Thank you for helping me to spot my error! Commented Dec 8, 2020 at 6:08
  • 1
    @FermiToh printf("const char *suit[%u] is: %s\n", i, *suit[i]); This can't be the real code. *suit[i] is a char and printing it with format %s can never result in those strings you quote. Commented Dec 8, 2020 at 6:10
  • @dxiv Yes apologies! It should not have that '*'! Thank you so much for spotting it! Commented Dec 8, 2020 at 6:17

4 Answers 4

2

A simple fix! You only have 4 elements in your array but are iterating 5 times. Trying to access suit[5] will throw a Segmentation Fault (on Linux) or an Access Violation (on Windows). These errors occur when your accessing memory you shouldn't be (if you tried to access 0xEABCC8, but you don't have access to it, you will get hit with one of these errors). Try changing your max bound to 4, instead of 5.
In C (and basically every other language) indexes start at 0 when indexing, but start at 1 when initalisation. Example:

const int foo[4] = { 6, 9, 3, 2}; // Creates an array with 4 elements.
foo[4] // Gets the fifth element since it start at zero,
foo[0] // thus this is the first element.
Sign up to request clarification or add additional context in comments.

9 Comments

Trying to access suit[5] I think you mean Trying to access suit[4]
@FermiToh Certainly! Well, suit is an array with a length of four. The type of data that suit contains are strings, which in and of themselves are an array (this time of characters). Thus *suit[4] means your taking the 4th string inside of the suit array, and the * symbol just returns a pointer to that. So in the end, you end up getting a pointer to an array of characters (aka. you get a pointer to a string). As far as I know, you shouldn't have to supply the * character. C should devolve it for you.
I see! So it's a POINTER to an ARRAY containing an ARRAY of characters (a string). Also, what about the memory location? If I am not wrong, each character in the string has it's own memory location right?
@MiloBanks Thank you so much! May I know, how can you then refer to EACH element in the string array? Let's say I want to print the address of 'H' 'e' 'a' 'r' 't'? Each alphabet (element) should have it's own address. P.S Upvoted your comments :')
Simple. In order to get each character one after the other, just loop over the string. If you want to get the size of the string on the fly so you know how long to iterate, simply: strlen(suit[i]). So for (int l = 0; l < strlen(suit[i]); l++) { printf("%c\n", suit[i][l]) }. Note that strlent is only for getting the length of strings, and if you want to get the length of an array, google it.
|
1

The largest index is 3. Your loop is trying to access index 4 which does not exist..

Sigh.

Comments

1

As you found that, in your code, the loop which is printing suit array strings is accessing array beyond its size. To not to repeat this mistake again, follow this mechanism to get the size of an array:

size_t sz = sizeof (arr) / sizeof (arr[0]);

In your case, you should do:

    for (size_t i = 0; i < sizeof (suit) / sizeof (suit[0]); ++i)
    {
        printf("const char *suit[%zu] is: %s\n", i, suit[i]);
    }

With this, if you change the size of suit array (adding or removing array members), you don't need to make any changes in the loop printing the suit array members.


Additional:

You don't need to specify the dimension when initialising an array. When we omit the dimension, compiler computes it for us based on the size of the initialiser. So, you can do:

const char *suit[] = { "Hearts", "Diammonds", "Clubs", "Spades" };
                ^^
                 |
           omit the dimension

To check it, you can do

#include <stdio.h>

int main(void)
{
    const char *suit[] = { "Hearts", "Diammonds", "Clubs", "Spades" };

    printf ("Size of suit array : %zu\n", sizeof (suit) / sizeof (suit[0]));

    return 0;
}

Output:

Size of suit array : 4

Comments

0

As many have pointed out, you are trying to access an element in the array that is not there.

You also need to change the print line to the following, as you are printing the string itself, and you are already de referencing the pointer by suit[i].

for (i = 0; i < 4; i++)
{
    printf("const char *suit[%lu] is: %s\n", i, suit[i]);
}

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.