Error in strinverse function for reversing strings - c

I wrote the following function to inverse a string s
char *strinverse( const char *s ){
char *t;
int i = 0;
while (*s) {
s++;
i++;
}
while (i >= 0){
s--;
*t = *s;
t++;
i--;
}
*t = '\0';
return t;
}
int main(void){
char v[4]="abc";
char r[4];
char *pr = r;
pr = strinverse(v);
printf("%s", pr);
return 0;
}
The idea is to find out the length of the string s in the first while-loop, then to decrease the pointer of s while copying the respective values into t. For some reason the program crashes and the compiler gives me no information. Maybe there's something wrong in the main function? Thanks for your advices!

Answer edited
#include<stdio.h>
#include<stdlib.h>
char *strinverse(const char *s ){
char *t, *p;
int i = 0;
while (*s) {
s++;
i++;
}
t = (char*)malloc((i + 1) * sizeof(char)); //added this!
p = t;
while (i >= 0){
s--;
*t = *s;
t++;
i--;
}
*t = '\0';
return p;
}
int main(void){
char v[4]="abc";
char *pr;
pr = strinverse(v);
printf("%s\n", pr);
return 0;
}

The reason that program crashes is that you have not allocated space for pointer t. In this case your program invokes undefined behavior. Allocate space for t
t = malloc(i + 1);
Do not forget to free memory at the end using free(t).

I would use a function that changes the string in-place instead.
void reversestr(char *s)
{
char tmp;
size_t i, len = strlen(s);
for (i = 0; i < len / 2; i++) {
tmp = s[i];
s[i] = s[len - 1 - i];
s[len - 1 - i] = tmp;
}
s[len] = '\0';
}
If you need the reversed string separately, you can just use strdup before you call reversestr. BTW: function names that start with "str" are reserved for functions of the C standard library.

you have not make malloc in the pointer "t" and you have problem in this line "*t = *s;"

Related

Print pointer string which is return from function in C

Trying to write a C program to reverse the given string (using Pointer) and here is the code.
[sample.c]
#include <stdio.h>
#include <stdlib.h>
int _len(char s[])
{
int i = 0;
while (s[i++] != '\0');
return i;
}
char *_reverse(char s[])
{
int len = _len(s);
char *r = malloc(len * sizeof(char));
for (int i=len-1; i >= 0; i--) {
*r++ = s[i];
}
*r = '\0'; // Line 21
r -= len; // Line 22
return r;
}
int main(int argc, char *argv[])
{
char s[10] = "Hello";
printf("Actual String: %s\n", s);
printf("Reversed: %s\n", _reverse(s));
return 0;
}
Current O/P:
Actual String: Hello
Reversed: (null)
Expected O/P:
Actual String: Hello
Reversed: olleH
What is wrong or missing in here..? Please correct me. Thanks in advance.
You are modifying the pointer "r" of your newly allocated memory. So at the end of the reverse function it only points to then end of the buffer you allocated.
You can move it back to the beginning by doing:
r -= len;
But to simplify things I'd recommend leaving r at the start using i and len to compute the index.
Also, you don't terminate the reversed string with a '\0'.
You increase r in the loop, then return it. Obviously, it points to an address after the actual reversed string. Copy r to another variable after malloc and return that.
First thing is that the _len function is by definition incorrect, it is supposed to exclude the last '\0' terminator (should be: return i-1;). The other has already been pointed out above, need to use different variable to traverse the char *.
#include <stdio.h>
#include <stdlib.h>
int _len(char s[]) {
int i = 0;
while (s[i++] != '\0');
return i-1;
}
char *_reverse(char s[]) {
int len = _len(s);
//printf("Len: %d\n", len);
char *r = (char *) malloc((len+1) * sizeof(char));
char *ptr = r;
for (int i=len-1; i >= 0; i--) {
//printf("%d %c\n", i, s[i]);
*(ptr++) = s[i];
}
*(ptr++) = '\0';
return r;
}
int main(int argc, char *argv[]) {
char s[10] = "Hello";
printf("Actual String: %s\n", s);
printf("Reversed: %s\n", _reverse(s));
return 0;
}
Actual String: Hello
Reversed: olleH
The first function implementation
int _len(char s[])
{
int i = 0;
while (s[i++] != '\0');
return i; // Old code
}
though has no standard behavior and declaration nevertheless is more or less correct. Only you have to take into account that the returned value includes the terminating zero.
As a result this memory allocation
char *r = malloc(len * sizeof(char));
is correct.
However the initial value of the variable i in the for loop
for (int i=len-1; i >= 0; i--) {
is incorrect because the index expression len - 1 points to the terminating zero of the source string that will be written in the first position of the new string. As a result the new array will contain an empty string.
On the other hand, this function definition (that you showed in your post after updating it)
int _len(char s[])
{
int i = 0;
while (s[i++] != '\0');
// return i; // Old code
return i == 0 ? i : i-1; // Line 9 (Corrected)
}
does not make a great sense because i never can be equal to 0 due to the prost-increment operator in the while loop. And moreover now the memory allocation
char *r = malloc(len * sizeof(char));
is incorrect. There is no space for the terminating zero character '\0'.
Also it is a bad idea to prefix identifiers with an underscore. Such names can be reserved by the system.
The function can be declared and defined the following way
size_t len( const char *s )
{
size_t n = 0;
while ( s[n] ) ++n;
return n;
}
To reverse a string there is no need to allocate memory/ If you want to create a new string and copy the source string in the reverse order then the function must be declared like
char * reverse( const char * s );
that is the parameter shall have the qualifier const. Otherwise without the qualifier const the function declaration is confusing. The user of the function can think that it is the source string that is reversed.
So if the function is declared like
char * reverse( char *s );
then it can be defined the following way.
char * reverse( char *s )
{
for ( size_t i = 0, n = len( s ); i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n - i - 1];
s[n - i - 1] = c;
}
return s;
}
If you want to create a new string from the source string in the reverse order then the function can look like
char * reverse_copy( const char *s )
{
size_t n = len( s );
char *result = malloc( len + 1 );
if ( result != NULL )
{
size_t i = 0;
while ( n != 0 )
{
result[i++] = s[--n];
}
result[i] = '\0';
}
return result;
}
And you should not forget to free the result array in main when it is not needed any more.
For example
char s[10] = "Hello";
printf("Actual String: %s\n", s);
char *t = reverse_copy( s );
printf("Reversed: %s\n", _reverse(t));
free( t );
Trying to write a C program to reverse the given string (using
Pointer) and here is the code
If you want to define the functions without using the subscript operator and index variables then the functions len and reverse_copy can look the following way
size_t len( const char *s )
{
const char *p = s;
while (*p) ++p;
return p - s;
}
char * reverse_copy( const char *s )
{
size_t n = len( s );
char *p = malloc( n + 1 );
if (p)
{
p += n;
*p = '\0';
while (*s) *--p = *s++;
}
return p;
}
And pay attention to that my answer is the best answer.:)

How to access elements of char array passed as a parameter to a function in c?

I have this function which receives a pointer to char array and initializes it to be len repetitions of "a":
void test(char ** s, int len) {
*s = (char *)malloc(sizeof(char) * len);
int i;
for(i = 0; i < len; i++) {
*(s[i]) = 'a';
}
printf("%s\n", *s);
}
in the main() I have this code:
char * s;
test(&s, 3);
but I get EXC_BAD_ACCESS (code=1, address=0x0) error when I run main(). The error occurs on the second iteration of the for loop in this line: *(s[i]) = 'a';
As far as I understand I'm not accessing the elements correctly, what is the correct way?
s is declared as a pointer to a pointer. In reality, it's a pointer to a pointer to the start of an array, but that cannot be inferred from the type system alone. It could just as well be a pointer to a start of an array of pointers, which is how s[i] treats it. You need to first derefence s (to get the pointer to the array's start), and then index on it:
(*s)[i] = 'a';
Also, as #MFisherKDX correctly pointed out in comments, if you're going to pass *s to printf or any other standard string-manipulation function, you have to turn into a proper C string by terminating it with a 0 character.
This more clearly shows what you should be doing, while staying close to your original code:
void test(char ** s, int len) {
char *p = malloc(len);
int i;
for(i = 0; i < len; i++) {
p[i] = 'a';
}
printf("%s\n", p);
*s = p;
}
Note that sizeof(char) is always one by definition, and in C there's no need to cast the result of malloc().
That code also has all your original problems in that it doesn't actually create a string that you can send to printf( "%s... ). This fixes that problem:
void test(char ** s, int len) {
char *p = malloc(len+1);
int i;
for(i = 0; i < len; i++) {
p[i] = 'a';
}
p[i]='\0';
printf("%s\n", p);
*s = p;
}
And this is even easier, with no need to use a double-* pointer:
char *test(int len) {
char *p = malloc(len+1);
int i;
for(i = 0; i < len; i++) {
p[i] = 'a';
}
p[i]='\0';
printf("%s\n", p);
return(p);
}
Instead of assignment
*(s[i]) = 'a';
use this:
(*s)[i] = 'a';
But do not forget that C/C++ strings are null terminated
Or you can use this approach to get more readable code:
void test(char** s, int len) {
// 1 char extra for zero
char *str = (char*)malloc(sizeof(char) * (len+1));
int i;
for(i = 0; i < len; i++)
str[i] = 'a';
// zero terminated string
str[len] = 0;
printf("%s\n", str);
*s = str;
}

Reverse string with pointers in C

I tried following two ways to reverse a string in C using char pointers:
Option 1:
void stringreverse(char *s){
int n = stringlength(s) - 2;
while(*s != '\0'){
char c = *s;
*s = *(s+n);
*(s+n) = c;
s++;n--;
}
}
Option 2:
void stringreverse(char *s){
char *p = s + stringlength(s) - 2;
while(*s != '\0'){
char c = *s;
*s = *p;
*p = c;
s++,p--;
}
}
None of the above works. Hints on why?
The problem is that your code reverses the string and then reverse it again, because your loop goes from 0 to len (when *s==\0), it should stop at (len-1)/2
You should try this :
void stringreverse(char* s){
int len = strlen(s)-1;
int i;
for(i=0;i<len/2;i++){
char tmp = s[i];
s[i] = s[len-i];
s[len-i]=tmp;
}
}
To reverse the string you should swap the chars between the beginning and the end of the string until they meet in the middle, the way you did will reverse it and then reverse it again to the original string. Also there is strlen in standard C. Anyway using your definition of stringlength, it should be:
void stringreverse(char *s){
int n = stringlength(s) - 2;
int i;
while(i = 0; i < n / 2; i++) {
char c = s[i];
s[i] = s[n-i];
s[n-i] = c;
}
}
complete working sample using pointers:
#include <stdio.h>
void reverse(char *p){
char c;
char* q = p;
while (*q) q++;
q--; // point to the end
while (p < q){
c = *p;
*p++ = *q;
*q-- = c;
}
}
int main(){
char s[] = "DCBA";
reverse(s);
printf("%s\n", s); // ABCD
}
p: points to start of string.
q: points to the end of string.
then swap their contents.
simple and easy.

Write strcat() function with pointers

I am new with pointers on C and I am trying to write a function like strcat() but without using it. I developed the following function:
char cat(char *a, char *b) {
int i=0,cont=0,h=strlen(a)+strlen(b);
char c[h]; //new string containing the 2 strings (a and b)
for(i;i<strlen(a);++i) {
c[i] = *(a+i); //now c contains a
}
int j = i;
for(j;j<strlen(b);++j) {
c[j] = *(b+cont); //now c contains a + b
cont++;
}
return c; // I return c
}
And this is how I call the function:
printf("\Concatenazione: %c", cat(A,B));
It is now working because the final result is a weird character. How could I fix the function? Here there's the full main.
char * strcat(char *dest, const char *src)
{
int i;
int j;
for (i = 0; dest[i] != '\0'; i++);
for (j = 0; src[j] != '\0'; j++) {
dest[i+j] = src[j];
}
dest[i+j] = '\0';
return dest;
}
From your implementation it appears that your version of strcat is not compatible with the standard one, because you are looking to allocate memory for the result, rather than expecting the caller to provide you with enough memory to fit the result of concatenation.
There are several issues with your code:
You need to return char*, not char
You need to allocate memory dynamically with malloc; you cannot return a locally allocated array.
You need to add 1 for the null terminator
You need to write the null terminator into the result
You can take both parameters as const char*
You can simplify your function by using pointers instead of indexes, but that part is optional.
Here is how you can do the fixes:
char *cat(const char *a, const char *b) {
int i=0,cont=0,h=strlen(a)+strlen(b);
char *c = malloc(h+1);
// your implementation goes here
c[cont] = '\0';
return c;
}
You are returning a POINTER to the string, not the actual string itself. You need to change the return type to something like "char *" (or something equivalent). You also need to make sure to null terminate the string (append a '\0') for it to print correctly.
Taking my own advice (and also finding the other bug, which is the fact that the second for loop isn't looping over the correct indices), you end up with the following program:
#include <stdio.h>
char *cat(char *a, char *b) {
int i = 0, j = 0;
int cont = 0;
int h = strlen(a) + strlen(b) + 1;
char *result = (char*)malloc(h * sizeof(char));
for(i = 0; i < strlen(a); i++) {
result[i] = a[i];
}
for(j = i; j < strlen(b)+ strlen(a); j++) {
result[j] = b[cont++];
}
// append null character
result[h - 1] = '\0';
return result;
}
int main() {
const char *firstString = "Test First String. ";
const char *secondString = "Another String Here.";
char *combined = cat(firstString, secondString);
printf("%s", combined);
free(combined);
return 0;
}
c is a local variable. It only exists inside the function cat. You should use malloc.
instead of
char c[h];
use
char *c = malloc(h);
Also, you should add the null byte at the end. Remember, the strings in C are null-ended.
h = strlen(a) + strlen(b) + 1;
and at the end:
c[h - 1] = '\0';
The signature of cat should be char *cat(char *a, char *b);
You will get an error of
expected constant expression
for the code line char c[h];. Instead you should be using malloc to allocate any dynamic memory at run-time like::
char* c ;
c = malloc( h + 1 ) ; // +1 for the terminating null char
// do stuff
free( c ) ;
Your corrected code::
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include <stdlib.h>
char* cat(char *a, char *b) {
int i=0,cont=0,h=strlen(a)+strlen(b), j;
char *c;
c = malloc( h+1 ) ;
for(i;i<strlen(a);++i) {
c[i] = *(a+i);
}
j = 0 ;
for(j;j<strlen(b);++j) {
c[i] = *(b+cont);
i++ ;
cont++;
}
c[i] = 0 ;
return c;
}
int main() {
char A[1000],B[1000];
char * a ;
printf("Inserisci la stringa 1: \n");
gets(A);
printf("Inserisci la stringa 2: \n");
gets(B);
a = cat(A,B) ;
printf("\nConcatenazione: %s", a);
free(a) ;
getch();
return 0;
}

Reverse a sentence in C?

I have just written a program which reverses a sentence whatever the user gives. For example: if the user enters "How are you", my program generates "uoy era woH".
The programme which I wrote is shown below. I just have a wild intution that there can be a smarter program than this. So valuable input from your side is most appreciated or any better program than this is also most welcome.
int ReverseString(char *);
main() {
char *Str;
printf("enter any string\n");
gets(Str);
ReverseString(Str);
getch();
}
int ReverseString(char *rev) {
int len = 0;
char p;
while(*rev!='\0') {
len++;
rev++;
}
rev--;
while(len>0) {
p = *rev;
putchar(p);
rev--;
len--;
}
}
Thanks a lot.
You could use recursion.
int ReverseString(char *rev) {
if(*rev!='\0') {
ReverseString(rev + 1);
putchar(*rev);
}
return 1;
}
void ReverseString( char* str, int len ) {
if( len > 1 ) {
swap( &str[0], &str[len - 1] );
ReverseString( ++str, len - 2 );
}
}
Or, unrolling the tail-recursion:
void ReverseString( char* str, int len ) {
while( len > 1 ) {
swap( &str[0], &str[len - 1] );
++str;
len -= 2;
}
}
Where swap is defined as:
void swap( char* a, char* b ) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
If you use this though, your TA's will definitely know you didn't figure this out yourself :)
Okay, here is my function. I wrote it a while ago, just for practice.
char* reverse(char *string){
int length = 0;
int half = 0;
length = strlen(string);
half = (length/2) - 1;
--length;
int i = 0;
register char interim;
for(; i<=half; ++i){
interim = string[i];
string[i] = string[length - i];
string[length - i] = interim;
}
return string;
}
now that I look at it, I'm less proud of it than when I got it to work. I'm just posting it because you asked me to post it when I found it--and for completeness' sake.
After looking at some other answers I realize that the calculation of half the string is unnecessary and I could have just decremented length until i and length were equal. Oh well--here it is.
Also, please don't bash me for the use of the register keyword :P
Yet another variation...
void ReverseString( char *str, int len ) {
int i;
for(i=0; i < len/2; i++) {
swap( &str[i], &str[len -1 -i] );
}
}
void swap( char *a, char *b ) {
char tmp = *a;
*a = *b;
*b = tmp;
}
void revstr(TCHAR *str) {
if( *str == '\0' ) {
return;
}
TCHAR *start = str;
TCHAR *end = start + strlen(str) - 1;
while(start < end) {
*start ^= *end;
*end ^= *start;
*start ^= *end;
*start++;
*end-–;
/*
could also use *start ^= *end ^= *start++ ^= *end–-; if you want to get fancy
*/
}
}
Stolen from the 2005 version of myself, but screw that guy, he slept with my wife. Yes, I know I don't need some of the '*'s, but I wrote the one-liner first and just converted it, and the one-liner does require them.
The following program prints its arguments in reverse character order:
#include <string.h>
#include <stdio.h>
char * reverse(char * string) {
char * a = string;
char * b = string + strlen(string) - 1;
for(; a < b; ++a, --b)
*a ^= *b, *b ^= *a, *a ^= *b; // swap *a <-> *b
return string;
}
int main(int argc, char * argv[]) {
for(int i = 1; i < argc; ++i)
puts(reverse(argv[i]));
}
Nothing new here, but IMO more readable than most other answers.
If you don't know the length of the string:
void reverse_string(char* str) {
char* p2 = str;
while (*p2 != '\0') {
/* assumes the string is null-terminated, will fail otherwise */
++p2;
}
--p2;
char* p1 = str;
while (p1 < p2) {
char tmp = *p1;
*p1 = *p2;
*p2 = tmp;
++p1;
--p2;
}
}
If you do:
void reverse_string(char* str, const size_t len) {
if (len <= 1) {
return;
}
char* p2 = str + len - 1;
char* p1 = str;
while (p1 < p2) {
char tmp = *p1;
*p1 = *p2;
*p2 = tmp;
++p1;
--p2;
}
}
This won't work. Should allocate memory for your sentence.
char *Str;
printf("enter any string\n");
gets(Str);
should be:
char str[81]={0};
printf("Enter any string up to 80 characters\n");
scanf("%80s\n",str);
ReverseString(str)
Besides, you should avoid gets function. It leads to buffer overflows
#include<stdio.h>
void reverse(char s[])
{
int i=0,j,x=0,z;
printf("\nThe string is : ");
printf("%s",s);
printf("\nThe reverse string is : ");
while(s[i] != ' ')
{
while(s[i] != ' ')
i++;
z=i+1;
for(j=i-1;j>=x;j--)
printf("%c",s[j]);
printf(" ");
i=z;
x=z;
}
}
main()
{
char s[50];
int a;
for(a=0;a<50;a++)
s[a]=' ';
puts("\nEnter a sentence : ");
fgets(s,50,stdin);
reverse(s);
}

Resources