2

Possible Duplicate:
In C++, Why can't I write to a string literal while I can write to a string object?

I'm having my first experience with wchar_t strings and I'm having a lot of trouble. Each time I try to access a character in an wchar_t* the program crashes with segmentation fault. How should I do if I want to replace one character in the string with another? But when deleting a character from the end of the string?

wchar_t * my_string[] = L"Hello";
my_string[0] = L'Y'; // Should be "Yello". Instead, gives segmentation fault

[edit] Doesn't matter, I've just made a fool out of myself. I'll check elsewhere on the internet. It's my fault, I shouldn't be bothering you with such silly questions...

Community
  • 1
  • 1
Petru Dimitriu
  • 365
  • 1
  • 5
  • 14
  • 1
    Without example code, this question is worse than useless. – Puppy Mar 31 '12 at 19:12
  • That code isn't even legal. The type of `my_string[1]` is `wchar_t*`, you can't assign a character value to a pointer variable. You also don't seem to understand zero-based indexing. – Ben Voigt Mar 31 '12 at 19:21
  • 1
    Fine then I should revise my C knowledge unless I want to make a fool out of myself. I knew about zero-based indexing but I'm used to working with other types of arrays from index 1. I just rushed and made a typo above. And this is true, I don't have much programming experience. – Petru Dimitriu Mar 31 '12 at 19:24

1 Answers1

4

You didn't supply much information, but, since you talk about segmentation fault, the most common errors derived from the fact that memory management functions usually works on bytes while wchar_t has a size greater than 1.

When doing pointer arithmetic over char, the sizeof(char) is almost never taken in count, since it is 1 by definition. But wchar_t is wider, hence where bytes length are required, a multiplication of sizeof(wchar_t) must be placed.

[EDIT] Sorry but the sample has nothing to do with wchar_t itself:

wchat_t* my_string[] is an arry of wchar_t-pointers, the first of which is made to point to "Hello", and the other are left uninitialized. Just remove the *.

TioneB
  • 468
  • 3
  • 12
Emilio Garavaglia
  • 20,229
  • 2
  • 46
  • 63
  • I've just added example code above... thanks for kind answer. – Petru Dimitriu Mar 31 '12 at 19:21
  • 1
    Thank you so much for the help, I seem to just be making a fool out of myself, showing off my poor experience. But what if I have a function which has wchar_t * (a wide char string) as one of its parameters and I want to make a change in it? – Petru Dimitriu Mar 31 '12 at 19:33
  • 2
    @PetruDimitriu wchar_t* are not semantically different from char* or from int*. If it points to 10 wchar_t and you want to change the 7th, just do ptr[6] = L'.'; The problem is that if ptr point to a literal (a string constant), you cannot change it since it is stored as read-only. – Emilio Garavaglia Apr 02 '12 at 06:52