Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy can't I assign values to pointers?
    primarykey
    data
    text
    <p>After reading the faq's and everything else I can find, I'm still confused. If I have a char pointer that is initialised in this fashion:</p> <p><code>char *s = "Hello world!"</code></p> <p>The string is in read-only memory and I cannot change it like this:</p> <pre><code>*s = 'W'; </code></pre> <p>to make "Wello world!". This I understand, but I can't, for the life of me, understand how to make it NOT read-only. Do I have to use an array instead of a pointer? Like <a href="https://stackoverflow.com/questions/164194/why-does-simple-c-code-receive-segmentation-fault">here</a>?</p> <p>This is my code: </p> <pre><code>char *s = str; char *e = s; while (*e != '\0') e++; e--; char *temp; //Swop the string around while (s &lt;= e) { *temp = *s; *s = *e; *e = *temp; e--; s++; } </code></pre> <p>The error message is just a segmentation fault. Apologies in advance if this is a really stupid question. </p> <p>Thanks so much for all the help. After taking all your advice, I get this:</p> <pre><code>void something(char * str) { char *store = str; char *s = new char[strlen(str) + 1]; //Allocate memory. Nice one. strcpy(s, str); char *e = new char[strlen(str) + 1]; strcpy(e, str); while (*e != '\0') e++; e--; char temp; //no longer a pointer while (s &lt;= e) { cout &lt;&lt; *e; temp = *s; *s = *e; *e = temp; e--; s++; } delete [] e; delete [] s; } </code></pre> <p>however, the deletes at the end of the function seem to be causing their own segmentation faults. Why? </p> <p>For interest's sake: The faults were due to accessing the e and s pointers after they were incremented. A much simpler solution followed from that:</p> <pre><code>void something(char * str) { char *s = new char[strlen(str) + 1]; strcpy(s, str); char temp; int j = strlen(str) - 1; for (int i = 0; i &lt;= strlen(str)/2; i++) { cout &lt;&lt; s &lt;&lt; endl; temp = s[i]; s[i] = s[j]; s[j] = temp; j--; } delete [] s; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload