How to reverse a string with pointers only? - c

I'm trying to reverse a string, but it just stays the same. I don't use any modules except <string.h> and <stdio.h>.
void rev(s){
char i, temp;
char *sf = s;
char ri = strlen((s) - 1);
char *sl = &s[ri];
for (i = 0; i < ri; i++){
if (*sf != *sl){
temp = *sf++;
s[i] = *sl--; //
s[ri--] = temp; //those two seems to be getting new characters, but it won't
}
else {
ri--;
sf++;
sl--;
}
}
printf("%s", s);
}

The function will not compile at least because the parameter does not have a type specifier.
void rev(s){
The type char has a little range of acceptable values. So you shall not use it for calculating the length of a string.
The call of strlen in this declaration
char ri = strlen((s) - 1);
invokes undefined behavior. It seems you mean
char ri = strlen(s) - 1;
that also can invoke undefined behavior for an empty string.
This loop
for (i = 0; i < ri; i++){
does not use pointers.
The function can be defined the following way as it is shown in the demonsytrative program below.
#include <stdio.h>
#include <string.h>
char * reverse( char *s )
{
if ( *s )
{
for ( char *first = s, *last = s + strlen( s ); first < --last; ++first )
{
char c = *first;
*first = *last;
*last = c;
}
}
return s;
}
int main( void )
{
char s1[] = "1";
char s2[] = "12";
char s3[] = "123";
puts( reverse( s1 ) );
puts( reverse( s2 ) );
puts( reverse( s3 ) );
}
The program output is
1
21
321

A simple solution:
char *sl = sf;
while (*sl != 0)
++ sl;
-- sl;
while (sf < sl)
{
char c = *sf;
*sf = *sl;
*sl = c;
++sf, --sl;
}
Find the end of the string by skipping all characters until you find the NUL (zero) character.
Then step back one character (decrement sl) so that you have pointers to the first and the last character of the string.
Then walk both pointers towards one another and swap characters until the pointers meet or cross.

Your code has plenty of issues (bugs 🐛):
char ri = strlen((s) - 1); has to be size_t ri = strlen((s)) - 1;
Other code is very hard to analyze as you use not self explanatory variable names.
Here you have a bit more simple code and much easier to analyse.
char *reverseString(char *str)
{
char *wrk = str, *end;
if(str && *str)
{
end = str + strlen(str) - 1;
while(end > wrk)
{
char temp = *wrk;
*wrk++ = *end;
*end-- = temp;
}
}
return str;
}
int main(void)
{
char str[] = "1234567890";
printf("reversed: %s\n", reverseString(str));
}

Related

C - Getting bus error when passing directly string in param

Making my own version of strtrim in C and its working fine but I wonder why it's working if I declare 2 array of char, like this:
static int is_set(const char *set, char c)
{
char *s;
s = (char *)set;
while (*s)
{
if (*s == c)
return (1);
s++;
}
return (0);
}
static char *ft_strsub(char const *str, unsigned int start, unsigned int end)
{
char *res;
char *s;
size_t size;
int i;
size = end - start;
res = malloc(size + 1);
if (!res)
return (res);
s = (char *)str + start;
i = 0;
while (*s && end-- > start)
res[i++] = *s++;
res[i] = 0;
return (res);
}
char *ft_strtrim(char const *s1, char const *set)
{
char *start;
char *s;
s = (char *)s1;
while (*s && is_set(set, *s))
s++;
if (!*s)
return (s);
start = s;
while (*s)
s++;
while (is_set(set, *--s))
;
if (*s)
*++s = 0;
return (ft_strsub(start, 0, s1 - s));
}
int main(void)
{
char tst[] = " xxxtripouille";
char tst2[] = " x";
char * s = ft_strtrim(tst, tst2);
printf("%s\n", s);
free(s);
return (0);
}
But not if I pass directly a string directly in param. I'm getting bus error if I do this
int main(void)
{
/*char tst[] = " xxxtripouille";
char tst2[] = " x";*/
char * s = ft_strtrim(" xxxtripouille", " x");
printf("%s\n", s);
free(s);
return (0);
}
I must have missed something in my training ^^Thank's in advance !
EDIT:
Thank's for reply !
Thank you for your advice, I took care to write them down, I thank you again, and I also found out why it wasn't working, it's because I'm trying to close the string and as you told me: it's a read-only string;
char *ft_strtrim(char const *s1, char const *set)
{
char *start;
char *s;
s = (char *)s1;
while (*s && is_set(set, *s))
s++;
if (!*s)
return (ft_strdup(s));
start = s;
while (*s)
s++;
while (is_set(set, *--s))
;
if (*s)
++s;
return (ft_strsub(start, 0, s - start));
}
Here's a few lines of code you might consider to replace your is_set() function:
static int matchAny( const char *set, char c ) {
const char *s = set;
for( ; *s && *s != c; s++ )
; // just searching
return *s != '\0'; // true = match found
}
Don't "cast away" const-ness unnecessarily. Exploit the "conditional" segment of the for() loop. Return is also a conditional: "If not reaching the end of the string of 'bad' characters, then 'c' was 'matched' in that string.
If you get "trimming the front" working, perhaps a simple "reverse string" can be used to "trim the back end, too", then "reverse string" once more. Re-use code that works.
Seeing this function, it can be made even simpler:
static int matchAny( const char *set, const char c ) {
while( *set && *set != c )
set++; // just searching
return *set != '\0'; // true = match found
}
Often the best solution is to use fewer resources (like variables) but to use them wisely. Then, flaws have fewer places to hide.
At least this statement does not make a sense
return (ft_strsub(start, 0, s1 - s));
because there can be passed a negative value s1 - s that will be converted to a very big positive value in the function ft_strsub because the corresponding parameter has an unsigned integer type.
Pay attention to that the compiler can issue a message that you are discarding the qualifier const as for example
char *s;
s = (char *)s1;
Also the function can return a pointer that does not point to a dynamically allocated array that you are tries to free with the function free
if (!*s)
return (s);
//...
free(s);

Is there an easy way to remove specific chars from a char*?

char * deleteChars = "\"\'.“”‘’?:;-,—*($%)! \t\n\x0A\r"
I have this and i'm trying to remove any of these from a given char*. I'm not sure how I would go about comparing a char* to it.
For example if the char* is equal to "hello," how would I go about removing that comma with my deleteChars?
So far I have
void removeChar(char*p, char*delim){
char*holder = p;
while(*p){
if(!(*p==*delim++)){
*holder++=*p;
p++;
}
}
*holder = '\0';
A simple one-by-one approach:
You can use strchr to decide if the character is present in the deletion set. You then assign back into the buffer at the next unassigned position, only if not a filtered character.
It might be easier to understand this using two indices, instead of using pointer arithmetic.
#include <stdio.h>
#include <string.h>
void remove_characters(char *from, const char *set)
{
size_t i = 0, j = 0;
while (from[i]) {
if (!strchr(set, from[i]))
from[j++] = from[i];
i++;
}
from[j] = 0;
}
int main(void) {
const char *del = "\"\'.“”‘’?:;-,—*($%)! \t\n\x0A\r";
char buf[] = "hello, world!";
remove_characters(buf, del);
puts(buf);
}
stdout:
hello world
If you've several delimiters/characters to ignore, it's better to use a look-up table.
void remove_chars (char* str, const char* delims)
{
if (!str || !delims) return;
char* ans = str;
int dlt[256] = {0};
while (*delims)
dlt[(unsigned char)*delims++] = 1;
while (*str) {
if (dlt[(unsigned char)*str])
++str; // skip it
else //if (str != ans)
*ans++ = *str++;
}
*ans = '\0';
}
You could do a double loop, but depending on what you want to treat, it might not be ideal. And since you are FOR SURE shrinking the string you don't need to malloc (provided it was already malloced). I'd initialize a table like this.
#include <string.h>
...
char del[256];
memset(del, 0, 256 * sizeof(char));
for (int i = 0; deleteChars[i]; i++) del[deleteChars[i]] = 1;
Then in a function:
void delChars(char *del, char *string) {
int i, offset;
for (i = 0, offset = 0; string[i]; i++) {
string[i - offset] = string[i];
if (del[string[i]]) offset++;
}
string[i - offset] = 0;
}
This will not work on string literals (that you initialize with char* x = "") though because you'd end up writing in program memory, and probably segfault. I'm sure you can tweak it if that's your need. (Just do something like char *newString = malloc(strlen(string) + 1); newString[i - offset] = string[i])
Apply strchr(delim, p[i]) to each element in p[].
Let us take advantage that strchr(delim, 0) always returns a non-NULL pointer to eliminate the the null character test for every interrelation.
void removeChar(char *p, char *delim) {
size_t out = 0;
for (size_t in; /* empty */; in++) {
// p[in] in the delim set?
if (strchr(delim, p[in])) {
if (p[in] == '\0') {
break;
}
} else {
p[out++] = p[in];
}
}
p[out] = '\0';
}
Variation on #Oka good answer.
it is better way - return the string without needless characters
#include <string.h>
char * remove_chars(char * str, const char * delim) {
for ( char * p = strpbrk(str, delim); p; p = strpbrk(p, delim) )
memmove(p, p + 1, strlen(p));
return str;
}

C program to concatenate two pointer strings with functions

#include <stdio.h>
#include <stdlib.h>
char concaten(const char *str1,const char *str2);
int main()
{
printf("%s",concaten("Code","blocks"));
return 0;
}
char concaten(const char *str1,const char *str2) {
int i=0,j=0;
char *result;
while(*str1){
result[i++]=str1[i++];
}
while(*str2){
result[i+j++]=str2[j++];
}
return result;
}
I wrote this function to get two strings and add them to another third string; I don't understand where I am going wrong, as it doesn't print anything.
There are a number of problems with your concaten function.
First, it should be returning a char* pointer, not a char; thus, the declaration should look like this:
char* concaten(const char* str1, const char* str2);
Next, the function will need to allocate memory in which to store the concatenated strings; this can be done with the malloc() function, and the number of characters required will be the sum of the lengths of the two input strings plus one, for the required nul-terminator.
Third, the logic of your two loops is wrong. You are incrementing i and j twice per loop but not incrementing either of the source pointers.
Finally, you must add a nul-terminator at the end of your new string.
Here's a version with the above fixes applied:
char* concaten(const char* str1, const char* str2)
{
int i = 0, j = 0;
char* result = malloc(strlen(str1) + strlen(str2) + 1); // allow space for nul-terminator
while (*str1) {
result[i++] = *str1++; // Only increment i once and "str1" once
}
while (*str2) {
result[i + j++] = *str2++; // Only increment j once and "str2" once
}
result[i + j] = '\0'; // Add required nul-terminator
return result;
}
Also, as you have allocated memory (with the malloc call), you should release that when you're done with the data, using a call to free. Here's how your main might work:
int main(void)
{
char* answer = concaten("Code", "blocks");
printf("%s", answer);
free(answer);
return 0;
}
Note: You can also remove the j variable entirely, and just re-use the result[i++] expression in the second loop. I've left it in so that you can more easily relate my code to your own.
Your function has the return type char
char concaten(const char *str1,const char *str2);
but within the function you are returning the variable result
return result;
declared like a pointer of the type char *
char *result;
So the compiler will issue a message that you are trying to convert a pointer to an integer.
The function must be declared like
char * concaten(const char *str1,const char *str2);
The pointer result is not initialized and has an indeterminate value. You need to allocate memory where you will write concatenated strings.
The while loops in the function will be infinite if str1 and/or str2 are not empty strings due to conditions
while(*str1){
and
while(*str2){
These statements
result[i++]=str1[i++];
and
result[i+j++]=str2[j++];
invoke undefined behavior not only because the pointer result is not initialized but also because there is no sequence point between left and write operands where there is used the postfix increment operator ++.
Also the result string must be zero terminated.
If you are not allowed to use standard C string functions then your function can be implemented for example the following way
char * concatenate( const char *str1, const char *str2 )
{
size_t n1 = 0;
size_t n2 = 0;
while ( str1[n1] ) ++n1;
while ( str2[n2] ) ++n2;
char *result = malloc( n1 + n2 + 1 );
if ( result != NULL )
{
char *p = result;
while ( *str1 ) *p++ = *str1++;
do
{
*p++ = *str2;
} while ( *str2++ );
}
return result;
}
Also you should not forget to free the allocated memory when the result string is not needed any more.
Here is a demonstrative program.
#include <stdio.h>
#include <stdlib.h>
char * concatenate( const char *str1, const char *str2 )
{
size_t n1 = 0;
size_t n2 = 0;
while ( str1[n1] ) ++n1;
while ( str2[n2] ) ++n2;
char *result = malloc( n1 + n2 + 1 );
if ( result != NULL )
{
char *p = result;
while ( *str1 ) *p++ = *str1++;
do
{
*p++ = *str2;
} while ( *str2++ );
}
return result;
}
int main(void)
{
char *result = concatenate( "Code ", "blocks" );
if ( result != NULL ) puts( result );
free( result );
return 0;
}
The program output is
Code blocks
If you may use standard C string functions then the function concatenate can look as it is shown in the demonstrative program below.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * concatenate( const char *str1, const char *str2 )
{
size_t n1 = strlen( str1 );
size_t n2 = strlen( str2 );
char *result = malloc( n1 + n2 + 1 );
if ( result != NULL )
{
memcpy( result, str1, n1 );
memcpy( result + n1, str2, n2 + 1 );
}
return result;
}
int main(void)
{
char *result = concatenate( "Code ", "blocks" );
if ( result != NULL ) puts( result );
free( result );
return 0;
}
The program output is the same as shown above that is
Code blocks
Aside from the fact that your function should not return char but char*, the expression result[i++] = str1[i++]; is not correct it lacks a sequence point. Furthermore result is an unitialized pointer, it cannot hold any data, you would need to make it point to some valid memory location.
You could do something like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* concatenate(const char* str1, const char* str2 ){
char* result = malloc(strlen(str1) + strlen(str2) + 1);
if (result){
char* temp = result;
while (*str1 != '\0'){
*temp++ = *str1++;
}
while (*str2 != '\0'){
*temp++ = *str2++;
}
*temp = '\0'; // don't forget to null terminate the string
}
return result; // if memory allocation fails a null pointer is returned
}
The direct usage of the function in the printf statement will not allow you to free the memory and you would have a memory leak if the program didn't finish immediately, in these cases it's best to have the returned pointer assigned as to not lose track of the allocated memory:
int main(void){
char *result = concatenate("Code", "blocks");
if(result){
printf("%s", result);
free(result);
}
return EXIT_SUCCESS;
}

String copy function not copying string properly. What's wrong with my code?

I'm trying to write a function that removes whitesapces from a string and convert it to lower case.
My code below doesn't return anything. Why?
char *removeSpace(char *st);
int main(void){
char *x = "HeLLO WOrld ";
x = removeSpace(x);
printf("output: %s\n", x);
}
char *removeSpace(char *st)
{
int c = 0;
char *s = malloc(sizeof(strlen(st)+1));
for (int x = 0; x < strlen(st); x++)
{
if (st[x] != ' ')
{
s[x] = tolower(st[x]);
}
}
st= s;
st= s;
return st;
}
The malloc statement uses sizeof unnecessarily as mentioned in the comments. You also have an error in the assignment of characters to the new string:
s[x] = tolower(st[x]);
You use the same index to the new string s as the old string st. This isn't right as soon as you remove any spaces. So for example indexes 0 through 4 line up between the two strings as you copy hello but then you skip a space at index 5 and then you want to assign the w at st[6] to s[5]. This means you need a separate index to track where you are in the destination string. So you need something like this code, which cleans up malloc(), adds the missing header includes, and introduces a new index for the output string:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char *removeSpace(char *st);
int main(void){
char *x = "HeLLO WOrld ";
x = removeSpace(x);
printf("output: %s\n", x);
}
char *removeSpace(char *st)
{
size_t len = strlen(st);
int newStrIdx = 0;
char *s = malloc(len+1);
for (int x = 0; x < len; x++)
{
if (st[x] != ' ')
{
s[newStrIdx++] = tolower(st[x]);
}
}
s[newStrIdx] = '\0';
return s;
}
Oh, and you forgot the null-terminate the output string, which I added at the end.
char *s = malloc(sizeof(strlen(st)+1));
you have a couple of nested expressions, and you jumped exactly the wrong way in the comment thread (I guess it was 50:50).
strlen(st) is the number of characters in the string st
strlen(st)+1 is the correct number of characters to allocate for a copy
... looking good so far!
sizeof(strlen(st)+1) is the size in bytes required to represent the type of that value. So if size_t is an 4-byte unsigned int, this sizeof expression is just 4.
The value of the string length is thrown away at this point.
Now, you want to allocate enough bytes for the string, not enough bytes to save the string's length as a size_t value. Just remove the sizeof entirely.
Oh, and also - st = s doesn't do anything here. The variable st is local inside the function, and doesn't affect anything outside. Returning s is sufficient.
For starters if you want to create a copy of a string then the function declaration shall look like
char * removeSpace( const char *st);
that is the original string is not changed within the function.
And as you are passing to the function a string literal
char *x = "HeLLO WOrld ";
x = removeSpace(x);
then indeed it may not be changed within the function. Any attempt to change a string literal results in undefined behavior.
The expression used in the call of malloc
sizeof(strlen(st)+1)
is equivalent to the expression
sizeof( size_t )
due to the fact that the function strlen has the return type size_t.
So this expression does not yield the length of the source string.
Moreover there is no need to allocate a string with the size equal to the size of the source string because the destination string can have much less characters (due to removing spaces) than the source string.
The assignment in the if statement
if (st[x] != ' ')
{
s[x] = tolower(st[x]);
}
uses an invalid index in the expression s[x]. That is as a result the destination string will contain gaps with uninitialized characters.
Also the terminating zero character '\0' is not appended to the destination string
Take into account that the set of white space characters includes other characters as for example the tab character '\t' apart from the space character ' '.
The function can be defined the following way.
char * removeSpace( const char *st )
{
size_t n = 0;
for ( const char *src = st; *src; ++src )
{
if ( !isspace( ( unsigned char )*src ) ) ++src;
}
char *result = malloc( n + 1 );
result[n] = '\0';
for ( char *dsn = result; *st; ++st )
{
if ( !isspace( ( unsigned char )*st ) )
{
*dsn++ = tolower( ( unsigned char )*st );
}
}
return result;
}
And the function can be called like
char *st = "HeLLO WOrld ";
char *dsn = removeSpace( st );
puts( dsn );
free( dsn );
Here is a demonstrative program.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char * removeSpace( const char *st )
{
size_t n = 0;
for ( const char *src = st; *src; ++src )
{
if ( !isspace( ( unsigned char )*src ) ) ++src;
}
char *result = malloc( n + 1 );
result[n] = '\0';
for ( char *dsn = result; *st; ++st )
{
if ( !isspace( ( unsigned char )*st ) )
{
*dsn++ = tolower( ( unsigned char )*st );
}
}
return result;
}
int main(void)
{
char *st = "HeLLO WOrld ";
char *dsn = removeSpace( st );
puts( dsn );
free( dsn );
return 0;
}
Its output is
helloworld

Is there any problem while returning the "char pointer" from function

The code below is expected to return a string containing only numbers from an user entered string.
Also the returned string should group the numbers in three digits and put a '-' between them.
Everything runs fine, code compiles without any error, but the char* is not being returned from function.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char* phoneNo(char*);
void main(){
char str[100];
char *strpass = str;
printf("Enter the string: ");
fgets(str,100,stdin);
printf("Entered stringis: %s\n",str);
char *result = phoneNo(strpass);
printf("Returned char* is: %s\n",result);
}
char* phoneNo(char *strpass){
char str[100];
strcpy(str,strpass);
printf("Char[] in Function: %s",str);
char answer[100];
char * result;
result = ( char* ) malloc(100*sizeof(char));
result=answer;
//printf("Char* pointed to Char[]: %s\n",result);
int i=0;
int j=0;
int k=3;
while(str[i]!='\0'){
if(str[i]=='1'||str[i]=='2'||str[i]=='3'||str[i]=='4'||str[i]=='5'||str[i]=='6'||str[i]=='7'||str[i]=='8'||str[i]=='9'||str[i]=='0')
{
if(j==0){
answer[j]=str[i];
answer[j+1]='\0';
j++;
i++;
continue;
}
if(j==k){
answer[j]='-';
answer[j+1]='\0';
j++;
k+=4;
}else{
answer[j]=str[i];
answer[j+1]='\0';
j++;
i++;
}
}
else
i++;
}
printf("Char* to be returned: %s\n",result);
return (char *)result;
}
This code snippet
char answer[100];
char * result;
result = ( char* ) malloc(100*sizeof(char));
result=answer;
has a memory leak because the address of the allocated memory is lost due to this statement
result=answer;
Now the pointer result points to the local array answer and returned from the function that results in undefined behavior because the array will not be alive after exiting the function.
Use the allocated dynamically array for processing instead of the local array answer.
Pay attention to that instead of this compound if statement
if(str[i]=='1'||str[i]=='2'||str[i]=='3'||str[i]=='4'||str[i]=='5'||str[i]=='6'||str[i]=='7'||str[i]=='8'||str[i]=='9'||str[i]=='0')
it is much better to write
if ( isdigit( ( unsigned char )str[i] ) )
And the function shall be declared like
char* phoneNo(const char *strpass);
that is its parameter must have the qualifier const.
I would write the function the following way as it is shown in the demonstrative program.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char * phoneNo( const char *s )
{
const size_t GROUP_SIZE = 3;
size_t digits_count = 0;
for ( const char *p = s; *p; ++p )
{
if ( isdigit( ( unsigned char )*p ) ) ++digits_count;
}
char *result = malloc( digits_count + digits_count / GROUP_SIZE + sizeof( ( char )'\0' ) );
size_t i = 0;
for ( size_t k = 0; *s; ++s )
{
if ( isdigit( ( unsigned char )*s ) )
{
if ( k == GROUP_SIZE )
{
if ( i != 0 )
{
result[i++] = '-';
}
k = 0;
}
result[i++] = *s;
++k;
}
}
result[i] = '\0';
return result;
}
int main(void)
{
const char *s = "123456789";
char *result = phoneNo( s );
puts( result );
free( result );
s = "12\t34567\t89";
result = phoneNo( s );
puts( result );
free( result );
return 0;
}
The program output is
123-456-789
123-456-789
First you allocate memory for result, then in the next line result=answer; you immediately have it point elsewhere, creating a memory leak while instead pointing at a local variable. This is the bug.

Resources