1

I have the following array of wide characters:

wchar_t alphabet[] = L"abcdefghijklmnñopqrstuvwxyz"; /*  array of wide characters */

Everytime I try to run the following code, a "segmentation violation" error occurs

printf("%ls %d\n", alphabet, wcslen (alphabet));
int i;
for (i = 0; i <= wcslen (alphabet); i++)
{
    printf("%ls\n", alphabet[i]);
}

How can I correct this error?

richardtk_1
  • 751
  • 3
  • 11
  • 33

2 Answers2

3

"%ls" causes alphabet[i] to be interpreted as a pointer to a string. Use "%lc".

ensc
  • 6,704
  • 14
  • 22
2

Your loop is overstepping the array.

Arrays are indexed from 0, so the condition in a loop like yours should always test with <, never with <=.

Also, you're printing single characters with %s, which is also wrong. It should be %lc for a single wide character.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • 2
    The `<=` is not the problem here (in the `==` case, it will deref the valid trailing L'\0'). – ensc Nov 19 '13 at 15:48
  • 1
    @unwind Surely the index of `alphabet[]` can range from `0 <= index <= wcslen (alphabet)`. Agree OP is unnecessarily printing the terminating `(wchar_t)0`, but that is not causing the "segmentation violation". Its the `%s` vs `%lc` that messes up things. – chux - Reinstate Monica Nov 19 '13 at 15:57