2
#include<stdio.h>
#include<string.h>

int main(int argc, char*argv[]){
    char buffer[256];
    strcpy(buffer, "see");
    int size = strlen(buffer);
   for(int i = 0; i < size; i++, size--){
      char temp = buffer[i];
      buffer[i] = buffer[size];
      buffer[size] = temp;
   }
   printf("Inversa %s\n",buffer);

}

The code dont print anything and i dont know why. If anyone can help me

1
  • 4
    buffer[size] is '\0' when first time. buffer[i] = buffer[size]; => buffer[0] = '\0'; Commented Apr 26, 2015 at 13:13

5 Answers 5

1

Since your i depends on size, do not modify it, instead take another variable, say l, and use it instead. Also, size of the string will be from 0 to size-1.

#include<stdio.h>
#include<string.h>

int main(int argc, char*argv[]){
char buffer[256];
strcpy(buffer, "see");

int size = strlen(buffer);
int l=size-1;
 for(int i = 0; i < size/2; i++, l--){
      char temp = buffer[i];
  buffer[i] = buffer[l];
  buffer[l] = temp;

 }
 printf("Inversa %s\n",buffer);

}
Sign up to request clarification or add additional context in comments.

Comments

1

As already mentioned, buffer[size] contains null character. And with your current code you fill buffer with nulls. Also, to reverse elements of array you should in loop go to size/2 instead of size. To reverse chars in array you could use following simple code

#include<stdio.h>
#include<string.h>

int main(int argc, char*argv[]){
    char buffer[256];
    strcpy(buffer, "see");
    int size = strlen(buffer);
   for(int i = 0; i < size/2; i++){
      char temp = buffer[i];
      buffer[i] = buffer[size-1-i];
      buffer[size-1-i] = temp;
   }
   printf("Inversa %s\n",buffer);
}

1 Comment

You never modify size, wouldn't you keep replacing the last character (buffer[size]=temp;) over and over again, or am I missing something?
0

Because string in C ends with \0, in the for cycle you push it to the start at first
This could be ok (but not tested)

  char temp = buffer[i];
  buffer[i] = buffer[size-1];
  buffer[size-1] = temp;

Comments

0

Just change line 10 and 11 of your code to :

buffer[i] = buffer[size-1];
buffer[size-1] = temp;

Reason is because value of variable 'size' is 3. so when you access buffer[size], It points to buffer[3] which is string termination character '\0'. Your buffer is filled only till buffer[2]. Example :

buffer[0]='s'
buffer[1]='e'
buffer[2]='e'
buffer[3]='\0' 

buffer[3] marks the end of string.

Comments

0

There's only one error in your code (invalid access of array, buffer[3]).

You need to change the line:

int size = strlen(buffer);

to

int size = strlen(buffer)-1;

or use buffer[size-1] instead of buffer[size]

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.