C reversing a String [duplicate] - c

This question already has answers here:
Segmentation fault occurring when modifying a string using pointers?
(8 answers)
Closed 9 years ago.
help me.. why this C program doesnt reverse the string ?
it crashes... but when i use a character array the code seems to work fine..but the moment i use a pointer to a string..its giving goosebumps...help me solve this..
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main(){
char *String="gokul";
char *Begin =String;
char *End = String + strlen(String) - 1;
char TempChar = '\0';
while (Begin < End)
{
TempChar = *Begin;
*Begin = *End;
*End = TempChar;
Begin++;
End--;
}
puts(String);
}

The problem is that String is pointing to a string literal, which is in read-only memory. You can still use a pointer for String, but it has to point to memory that can be modified.
char gokul[] = "gokul";
char *String = gokul;
Edit to address some minor issues.
There is no need to include the non-standard header conio.h in your program.
Your code does not handle the case where String is NULL.
Your loop is technically incorrect if String is an empty string, since End would point before the string.
main() should return a value, since it is declared to do so. 0 indicates success. Newer C compilers will know that the latest C Standard allows a program to hit the end of main() without return to mean to implicitly return a 0 for you.
#include<stdio.h>
#include<string.h>
int main(){
char gokul[] = "gokul";
char *String=gokul;
if (String && *String) {
char *Begin =String;
char *End = String + strlen(String) - 1;
char TempChar = '\0';
while (Begin < End)
{
TempChar = *Begin;
*Begin = *End;
*End = TempChar;
Begin++;
End--;
}
puts(String);
}
return 0;
}

Related

trying copy character from pointer to string [duplicate]

This question already has an answer here:
String literals: pointer vs. char array
(1 answer)
Closed 2 months ago.
I am trying to reverse string using pointer (ref source). in function
string_reverse
Bus Error happened at this line when copying character from char pointer end to start char pointer :
*start = *end;
I tried LLDB in VS code. .
Can some one explain why there is bus error happened at below line?
*start = *end
Full code below:
#include <stdio.h>
#include <string.h>
void string_reverse(char* str)
{
int len = strlen(str);
char temp;
char *end = str;
char *start = str;
/* Move end pointer to the last character */
for (int j = 0; j < len-1; j++)
{
end++;
}
for(int i = 0; i< len/2;i++ )
{
temp = *start;
*start = *end;
*end = temp;
/* update pointer positions */
start++;
end--;
}
}
int main( void )
{
char *str = "test string";
printf("Original string is %s\n", str);
string_reverse(str);
printf("Reverse string is %s\n", str);
return 0;
}
Actual result: Bus Error happened at line
*start = *end;
Expected output:
Reverse string is gnirts tset
The error happens because
char * str = "...";
mean you have a pointer to a string literal. It's a constant string that you can not modify.
When you change it to
char str[] = "...";
as chux-reinstate-monica mentioned, str will be char array with the length of your string, and you can modify it without any error.

Concatenate two string program not giving correct output

#include<stdio.h>
char * sstrcat(char*,char*);
void main() {
char *c;
char s[100] = "abcde";
char t[] = "fghi";
c = sstrcat(s,t);
printf("%s",c);
}
char* sstrcat(char *s,char *t) {
char* temp = s;
while(*s++ != '\0');
while((*s++ = *t++) != '\0');
return temp;
}
Above written code I am getting output abcde but expected output is concatenation of string s and t.
Please help me to figure out what mistake I am doing ?
thanks.
This line
while(*s++ != '\0');
will increment s after the comparison has been made, leaving '\0', which is a string terminator in your array.
If you can use a debugger you will find that all values are in your array, its just that printf will stop at '\0'
Just move your string iterator back one char due to '\0' (after you execute while(*s++ != '\0');) and that fixes your code.
Explanation:
Your s string is "abcde\0". After the first while loop, the iterator will be at '\0'. If you leave it there you will concatenate both strings obtaining the result "abcde\0fghi\0" which prints "abcde" due to the first '\0'.
Instead, if you move back the s string iterator one position with (s--) you will have this string as result "abcdefghi\0" which prints the string as you expect.
Fixed Code:
#include<stdio.h>
char * sstrcat(char*,char*);
void main() {
char *c;
char s[100] = "abcde";
char t[] = "fghi";
c = sstrcat(s,t);
printf("%s\n",c);
}
char* sstrcat(char *s,char *t) {
char* temp = s;
while(*s++ != '\0');
s--;
while((*s++ = *t++) != '\0');
return temp;
}

Segmentation fault when detabing string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a function to replace tabs with spaces in a string that looks like this:
#include <stdio.h>
char *detab(char *string)
{
for (int i = 0; string[i] != '\0'; i++)
if (string[i] == '\t')
string[i] = ' ';
return string;
}
int main(int argc, char **argv)
{
char *string = "\thello\thello";
detab(string);
printf("%s\n", string);
return 0;
}
But when I run it on "\thello\thello\t", it produces a segmentation fault. Why does it do this? I'm pretty new to C, so I may be missing something trivial.
This could be because the calling code did not allocate enough space for the string. It must always allocate at least one space larger than the visible characters in the string to allow space for the \0.
That being said, since strings are mutable, there is no need to return the string. It it will modify the string as you are working.
Here would be a working version of your code:
void detab(char * myStr)
{
for (int i = 0; myStr[i] != '\0'; i++)
if (myStr[i] == '\t')
myStr[i] = ' ';
}
char theString[] = "\thello\thello\t";
printf("Before: %s", theString);
detab(theString);
printf("After: %s", theString);
Also, keep in mind the following:
char buffer[4] = "test"; //THIS IS NOT SAFE. It might work, but it will overwrite stuff it shouldn't
char buffer[5] = "test"; //This is Ok, but could be an issue if you change the length of the string being assigned.
char buffer[] = "test"; //This is preferred for string literals because if you change the size of the literal, it will automatically fit.
UPDATE: Base on the main method you added, here is your issue:
You need to change
char * string = "\thello\thello";
To
char string[] = "\thello\thello";
The reason is because, when you define a string literal and assign it to a char *, it resides in the text portion of memory, and cannot be modified safely. Instead, you should assign the string literal to a char [] (which can be passed as a char * since that is what its actual type is). This syntax will let the compiler know it should allocate space on the stack and populate it with the values in the string literal, allowing it to be modified.
char * joe = "blah" simply creates the char * pointer, and points it to the data in the text portion (which is immutable).
char joe[] = "blah" tells the compiler to create an array of the appropriate length on the stack, to load it with the string literal, to create the char * pointer, and then to point the pointer at the start of the array of data on the stack.
This works:
#include <stdio.h>
#include <string.h>
char *detab(char *string)
{
for (int i = 0; string[i] != '\0'; i++)
if (string[i] == '\t')
string[i] = ' ';
return string;
}
int main ( int argc, char ** argv ) {
char str[21] = "\thello\thello\t";
printf( "%s\n", detab( str ) );
return 0;
}
As others have said, it's probably segfaulting because you're modifying a string literal. With char str[21], the string literal is copied into the stack-allocated str, where it can then be modified by your function.
Are you sure the strings are always null terminated.
Try some belt and braces...
char *detab(char *string)
{
int s_len= strlen(string) + 1;
for (int i = 0; string[i] != '\0'; i++)
{
if (string[i] == '\t')
{ string[i] = ' '; }
if (i == s_len) { /* failure - print some diagnostic */ return NULL; }
}
return string;
}

Reverse a string of any length using pointers in C [duplicate]

This question already has answers here:
How do you reverse a string in place in C or C++?
(21 answers)
How to read unlimited characters in C
(3 answers)
Closed 9 years ago.
I was just browsing through some interview questions and found this code to reverse a string using pointers. But I see that here they have defined char string[100] which limits the string length. I am not so good at C. How do I modify the same to make it a string of any length?
#include<stdio.h>
int string_length(char*);
void reverse(char*);
main()
{
char string[100];
printf("Enter a string\n");
gets(string);
reverse(string);
printf("Reverse of entered string is \"%s\".\n", string);
return 0;
}
void reverse(char *string)
{
int length, c;
char *begin, *end, temp;
length = string_length(string);
begin = string;
end = string;
for ( c = 0 ; c < ( length - 1 ) ; c++ )
end++;
for ( c = 0 ; c < length/2 ; c++ )
{
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
int string_length(char *pointer)
{
int c = 0;
while( *(pointer+c) != '\0' )
c++;
return c;
}
Instead of static array use dynamic memory allocation: char *tab = malloc(n * sizeof(char)) where n is some variable representing desired length.
You can use malloc() for this purpose if you want the size to be decided/inputted by the user at runtime.
malloc()
Dynamic memory allocation is the solution..
Take a pointer to the string and allocate the memory dynamically.. this allocates at run time..
This will solve your problem..
char *str;
str = (char*)malloc(n *sizeof(char));
NOTE: typecasting is optional in C and 'n' here is the required length.(can be user input).

segmentation fault when swapping pointer values while reversing a string [duplicate]

This question already has answers here:
Why is this string reversal C code causing a segmentation fault? [duplicate]
(8 answers)
Closed 9 years ago.
I am trying to reverse a string. I take two pointers , one pointing to the start of the string and other at the end of the string . And then I swap the values of the pointers.
int main()
{
char *string = "stack overflow";
int len = strlen(string);
char *end;
char tmp; //temporary variable to swap values
//pointer pointing at the end of the string
end = string+len-1;
printf(" value of start and end %c %c", *string , *end); //correct values printed
while(string<end)
{
tmp = *string;
*string = *end; //segmentation fault
*end = tmp;
*string++;
*end--;
}
return 0;
}
char *string = "stack overflow";
This creates a read-only string literal. Modifying it is undefined behavior. Use an array instead:
char string[] = "stack overflow";

Resources