Reputation: 63
I'm brand new to C. I've been going through exercises in a book I found, and have been having a lot of trouble understand strings. For this program, I'm simply trying to reverse a string that is read from user input.
The code I currently have:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 300
void reverseStr(char *str, int len){
int i;
char temp[len];
for (i = len; i >= 0; i--){
strncat(temp, &str[i], 1);
}
strcpy(str, temp);
}
int main(){
char *buffer;
size_t buffsize = 32;
size_t characters;
while (characters != 1){
buffer = (char *)malloc(buffsize * sizeof(char));
if ( buffer = NULL){
perror("Unable to allocate buffer");
exit(1);
}
printf("Type something: ");
characters = getline(&buffer, &buffsize, stdin);
printf("%zu characters were read.\n", characters);
printf("You typed: %s", buffer);
reverseStr(buffer, buffsize);
printf("backwards: %s\n", buffer);
}
}
What I currently have does reverse the string, but it also prepends a bunch of, what I assume to be null characters in the beginning.
Sample input/output:
Type something: sdf
4 characters were read.
You typed: sdf
backwards: 0s����
fds
As you can see, sdf
does return fds
as it should, but with extra unwanted characters prepended to it.
To further add to my confusion, I have gotten this to work properly before in another program I made.
/* This should be compiled with -ansi flag */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 3000
void reverseStr(char str[MAX], int len);
int getline(char s[], int lim);
int main(){
/* Read below on why we use a char array instead of a string,
* it's very important we understand this */
char line[MAX];
int len = strlen(line)-1;
while((len=getline(line, MAX))>0){
len = strlen(line)-1;
reverseStr(line, len);
printf("%s\n", line);
}
}
void reverseStr(char str[MAX], int len){
int i;
char temp[len];
for (i = len; i >= 0; i--){
strncat(temp, &str[i], 1);
}
strcpy(str, temp);
}
int getline(char s[],int lim){
int i,c;
for(i=0;i<lim-1 && (c=getchar())!=EOF && c!='\n';++i)
s[i] = c;
if( c == '\n')
{
s[i]=c;
++i;
}
s[i]='\0';
return i;
}
Output of second program:
sdf
fds
sdfsdfsdf
fdsfdsfds
The getline()
in the second program is taken straight from the book. I'm guessing this must be an old, deprecated way of doing things though? It appears to be a built-in function in later versions of C.
Upvotes: 0
Views: 104
Reputation: 552
This can more easily be done by just copying in the characters in reverse, then adding a NULL terminating byte at the end.
#include <stdio.h>
#include <string.h>
void reverse_string(char *str, char *rev_str) {
int j = 0, i;
for (i = strlen(str) - 1; i >= 0; i--) {
rev_str[j++] = str[i];
}
rev_str[j] = '\0';
}
int main() {
char *str = "123456789";
char rev_str[strlen(str)];
printf("%s\n", str);
reverse_string(str, rev_str);
printf("%s\n", rev_str);
return 0;
}
Output:
123456789
987654321
Upvotes: 2