Why is this string reversal code not working?
#include <stdio.h>
#include <stdlib.h>
void reverse(char* str) {
if (str) {
char* start;
char* end;
char temp;
start = str;
end = str;
while (*end != '\0') {
end++;
}
end--;
while (start < end) {
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
}
int main() {
char* str = "Hello World!";
reverse(str);
printf(str);
getchar();
}
I tried everything. What's wrong?
Omg I fixed it thnx /g/
Solution: I am retarded
>>62483964
>while (*end != '\0') {
>end++;
>}
>end--;
>>62483964
UNIRONICALLY USING VISUAL STUDIO
>>62484022
So I keep moving end forward until it becomes equal to the null character, then I pull it back once to point to the last character in the string. Is there something I am not seeing?
I hate having to use visual studio, anyone wanna recommend something else with a c++ window builder? all the ones on google fucking cost money.
>>poorfag yes
you're trying to write to read only memory
the memory for "hello world" is not writable
use strdup and don't forget to free
>>62484114
OP Here.
When I replace
> char* str = "Hello World!";
with
> char str[] = "Hello World!";
it works fine. You are right!
>>62483964
>if (str) {
>the entire function
>}
Brainlet Lmao, check your pointer, it should be an array....imbecile
>>62484078
use strlen
>>62484338
you're a faggot, as it is always the case for tripfags
>>62483964
Look at this filth.
>>62483964
lel
>>62483964
Here, I optimized for you:#include <stdio.h>
void main(){
printf("!dlroW olleH");
}
>>62484385
DON'T
EVER
USE
strlen
EVER
use strnlen instead. It's safe.
>>62483964
Just stick to Java, my street-shitting friend.
>>62483964
Next time use [ code ] [ /code ] tags
>>62484825unsigned int length(char* str) {
unsigned int len = 0;
while(str) {
len++;
}
len--;
return len;
}
>>62483964
Tell my how shit my function is, its been a long time since Ive done anything. I feel like this wouldnt even compile. maybe think of it as a concept or blueprint if that helps you hate me less.aaaaaaaaa(stuff){
char* adsf[strlen(str)] = str;
int a=0;
for(int i=strlen(str); i>0; i--){
asd[a] = str[i];
a++;
}
> if (str) {
...
> while (*end != '\0') {
> end++;
> }
> end--;
> these are the brainlets trying to take my job
o i am laffin
>>62485122
you're trying to declare an array of pointers with a runtime length
>>62485188
Yea, I had a feeling that wouldnt work. I also didnt need to put =str on there. iirc that never worked either.
I also feel my variable types dont even work the way i was trying to use them
>>62485221
https://cdecl.org/
if you're ever in doubt
>>62485123
What's wrong with this?
>>62485310
there's a standard function for this
>>62485257
Ill check it out, seems neat thanks.
>>62485257
Is copying a character like this invalid?
char array1[5]
char array2[5]
array2[i] = array1[i];
It wont fucking work with gcc or g++, yet Im looking at some code I wrote years ago and it works with mingw
>>62485367
Which is?