supra
supra

Reputation: 51

Error how to print array of char in C

#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

Upvotes: 2

Views: 89

Answers (5)

kvorobiev
kvorobiev

Reputation: 5070

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);
}

Upvotes: 1

Jahid
Jahid

Reputation: 22438

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]

Upvotes: 0

Ayushi Jha
Ayushi Jha

Reputation: 4023

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);

}

Upvotes: 1

user3521144
user3521144

Reputation: 43

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.

Upvotes: 0

maskacovnik
maskacovnik

Reputation: 3084

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;

Upvotes: 0

Related Questions