i am trying to do string reverse in a diffrent way - c

**i am trying to reverse a string so what i am trying is to take the string to its last position and from there i am storing it to a new character array and printing that but not getting desired output **
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char c[10];
printf("Enter the string:\n");
gets(c);
rev(c);
return 0;
}
void rev(char c[])
{
int i = 0,j = 0;
char s[10];
while(c[j] ! = '\0')//reaching to end of string
{
j++;
}
while(s[i] ! = '\0')
{
s[i] = c[j];//copying string c from end into string s from begining
i++;
j--;
}
s[i+1]='\0';
printf("The string after reverse: %s",s);//printing reversed string
}

while(s[i] ! = '\0')
In above line s[i] is uninitialized and hence you are invoking undefined behaviour by accessing uninitialized value and thus incorrect result.
To fix this, you can rewrite the condition as:
while(j >= 0)
Apart from these, for sane result, you need following two changes:
The final termination should be re-written as:
s[i]='\0';
The initial value of j should be decremented by 1. (As c[j] would point to the null character)
as i is now already pointing past the size of c string.

problem is when you use gets() the buffer is usually dirty. I would suggest you use fflush(stdin) before the gets().
Also the last line where you say s[i+1] = '\0' should be s[i] = '\0' the i already was incremented by one after the last execution of the loop.
And as said above it shouldnt be while (s[i] != '\0')
s is not initialized so God knows whats in there. make it like while ( j >=0) and it should work.

Related

How to create a function that changes characters of a string?

I'm new to coding and I've been studying C recently. Basically, I wanted to create the following function, which modifies every string element:
char *stralt(char *s, char ch)
{
int i;
for (i=0; i!='\0'; i++)
s[i] = ch;
return s;
}
And when I try to use it on int main(), like this:
int main()
{
printf("%s", stralt("test",'x'));
}
The prompt shows "test" instead of "xxxx". What is wrong with this code and how could it work properly?
Thanks!
You have two problems, one of which isn't apparent because the other doesn't allow it to occur.
You have:
for (i = 0; i != '\0'; i++)
Here, you compare the value of i against '\0', which is 0. Since i is 0 at the beginning of the for loop, the condition i != '\0' will be false, and the loop will exit before entering the body.
It seems that you meant to say:
for (i = 0; s[i] != '\0'; i++)
The other problem is that you're trying to modify a string literal. s[i] = ch; is invalid if s points to a string literal, as it does in your example.
Instead, you have to have a modifiable array of characters. This could be accomplished by modifying your main like:
int main()
{
char test_str[] = "test";
printf("%s", stralt(test_str, 'x'));
}

Program to get an indefinite number of strings in C and print them out

As part of an assignment, I am supposed to write a small program that accepts an indefinite number of strings, and then print them out.
This program compiles (with the following warning
desafio1.c:24:16: warning: format not a string literal and no format arguments [-Wform
at-security]
printf(words[i]);
and it prints the following characters on the screen: �����8 ���#Rl�. I guess it did not end the strings I entered by using getchar properly with the null byte, and it prints out garbage. The logic of the program is to initiate a while loop, which runs untill I press the enter key \n, and if there are an space, this is a word that will be store in the array of characters words. Why am I running into problems, if in the else statement once a space is found, I close the word[i] = \0, in that way and store the result in the array words?
#include <stdio.h>
#include <string.h>
int main()
{
char words[100][100];
int i,c;
char word[1000];
while((c = getchar()) != '\n')
{
if (c != ' '){
word[i++] = c;
c = getchar();
}
else{
word[i] = '\0';
words[i] == word;
}
}
int num = sizeof(words) / sizeof(words[0]);
for (i = 0; i < num; i++){
printf(words[i]);
}
return 0;
}
Here are some fixes to your code. As a pointer (as mentioned in other comments), make sure to enable compiler warnings, which will help you find 90% of the issues you had. (gcc -Wall)
#include <stdio.h>
#include <string.h>
int main() {
char words[100][100];
int i = 0;
int j = 0;
int c;
char word[1000];
while((c = getchar()) != '\n') {
if (c != ' '){
word[i++] = c;
} else {
word[i] = '\0';
strcpy(words[j++], word);
i = 0;
}
}
word[i] = '\0';
strcpy(words[j++], word);
for (i = 0; i < j; i++) {
printf("%s\n", words[i]);
}
return 0;
}
i was uninitialized, so its value was undefined. It should start at 0. It also needs to be reset to 0 after each word so it starts at the beginning.
The second c = getchar() was unnecessary, as this is done in every iteration of the loop. This was causing your code to skip every other letter.
You need two counters, one for the place in the word, and one for the number of words read in. That's what j is.
== is for comparison, not assignment. Either way, strcpy() was needed here since you are filling out an array.
Rather than looping through all 100 elements of the array, just loop through the words that have actually been filled (up to j).
The last word input was ignored by your code, since it ends with a \n, not a . That's what the lines after the while are for.
When using printf(), the arguments should always be a format string ("%s"), followed by the arguments.
Of course, there are other things as well that I didn't fix (such as the disagreement between the 1000-character word and the 100-character words). If I were you, I'd think about what to do if the user entered, for some reason, more than 1000 characters in a word, or more than 100 words. Your logic will need to be modified in these cases to prevent illegal memory accesses (outside the bounds of the arrays).
As a reminder, this program does not accept an indefinite number of words, but only up to 100. You may need to rethink your solution as a result.

Why do I get string of seemingly random number from this code?

#include <stdio.h>
#define LIM 1
int main(int argc, char const *argv[]) {
int i;
int c;
char s[LIM];
for (i=0; i < LIM-1 && (c=getchar()) != '\n' && c != EOF; ++i)
{
s[i] = c;
}
printf("%d\n", s);
return 0;
}
The output is for instance: 1541348039
I am expecting it to be 1.
printf("%d\n",*s)
or
printf("%d\n",s[0])
Right now you are trying to print the address of s. s is an array of one character so you need to point to the element you want to print.
Edit:
Also, you need to increment the value of LIM because the condition inside the for is always false.
There are two issues with your code. The first one is that you have to change the condition i < LIM-1 in your code to i < LIM, otherwise the loop will never run, because LIM-1 is equal to 0 and i is never less than 0.
The second issue is with the printf. If you do printf("%d\n", s); then you are asking C to print s as an integer. In this case, this will print the memory address of s. What you want is
printf("%c\n", s[0]);
which will print the only character of s. Note that you might want to make s a null terminated string, in which case you could print all of it (not just the first character) with:
printf("%s\n", s);
Of course making s a null terminated string would require to increase its size, since you would need an extra character for the null. Also, in that case, you have to use the i < LIM-1 condition in the loop to leave room for the null byte.

which code is better ? and how do we understand that ? why is the final print function in the second code sometimes printing random numbers?

I am very new here .. so please excuse me if my question is really unnecessary .. but I think the answer will help me have some faith in myself ..here are two code snippets ..one i got on the website c4learn.com ..
#include<stdio.h>
int main()
{
char s1[100], s2[100];
int i;
printf("\nEnter the string :");
gets(s1);
i = 0;
while (s1[i] != '\0')
{
s2[i] = s1[i];
i++;
}
s2[i] = '\0';
printf("\nCopied String is %s ", s2);
return (0);
}
and the other i wrote myself ..
#include<stdio.h>
int main()
{
char s1[100], s2[100];
int i;
printf("\n Enter the string 1");
gets(s1);
printf("\n Enter the string2");
gets(s2);
for(i=0;i<100;i++)
{
if (s1[i]!='\0')
{
s2[i]=s1[i];
}
}
s2[i]='\0';
printf("\n Copied string is %s ", s2);
return(0);``
}
the problem is while running the code on dev c++ .. the final printf displayed is showing some random characters at the end of the string .. Can anyone help me understand that and which is code is better ? the initial question was ... HOW WILL YOU COPY ONE STRING TO ANOTHER WITHOUT USING ANY INBUILT LIBRARIES ? thank you ..
Your code is not quite right:
Why do you ask for the user input for s2 if you then overwrite it, copying s1?
The for cycle you wrote doesn't stop when s1 is over (I mean the null terminator character '\0') so you are also copying all the chars remaining in s1 after '\0'. If the chars in the array are not initialized (and that's the case for chars after '\0') they of course might result in random characters.
So answering your question, the first code is the right way to do it.
Any way if you want to use a for cycle you could do:
for (i = 0; i < 100; i++) {
s2[i] = s1[i];
if (s1[i] == '\0')
break;
}
You have to break out of the loop when you reach the null terminator character \0. The first code breaks out of the while loop while you're code continues on until i == 100 skipping over the null character. This is why its printing garbage past the original string.
This is what you should do to break out after the null character.
for (i = 0; i < 100; i++) {
s2[i] = s1[i];
if (s1[i] == '\0') break;
}
In the second block of code, after exiting the for loop, i has a value of 100. So you're putting the 0 byte at index 100.
Since an array of size 100 has indexes 0 to 99, you're writing past the end of the array. That causes undefined behavior.
When you're inside of the for loop, you need to break out after you find the null byte.
Also, both programs use gets which is unsafe because it does not perform any bounds checking and may write past the end of the array.

why below code is giving garbage value?

why following code is giving garbage value ?
here I am trying to get an string as an input from user character by character. In the following code i have got input from user and stored in string[] array then in order to do some other operations i have stored the same in other array called temp_string[i]. But surprisingly i am getting garbage value in output.and also length calculated using strlen is not correct. can anybody look at this code and explain whats going wrong?
#include<stdio.h>
#include<stdio.h>
int main()
{
char ch;
int i = 0, j = 0;
int length = 0;
int lengthsb = 0;
char string[100];
printf(" Enter the string to divide\n ");
while(ch != '\n')
{
ch = getchar();
string[i] = ch;
i++;
}
char temp_string[i];
printf("%s", string);
i = 0;
while(string[i] != '\n')
{
temp_string[i] = string[i];
i++;
}
length = strlen(temp_string);
printf("Entered string is %s and its length is %d\n", temp_string, length);
}
You forgot to add the null at the end of the string.
C strings are null-terminated, that means that all operations in c strings expect a null to mark the end of the string, including functions like strlen.
you can achieve that just adding:
string[i] = '\0';
After fill the string.
Another thing, what happens if the user enters a string bigger than 100? Is good to validate the input for these cases, otherwise you can get a buffer overflow.
You need to add a NULL - terminated at the end of your string. Add \0.
You need to put a '\0' char at the end of the string so strlen(), printf() and other C functions dealing with strings will work. That is how the C API knows it reached the end of the string.
Also, you don't want to set new characters at the memory space past the string array. So you better check that in your loop (and save a last array item to set the '\0').
while (ch != '\n' && i < 99)
{
ch = getchar();
string[i] = ch;
i++;
}
string[i] = '\0'; // set the string terminator past the end of the input
Remember to do the same after copying the characters to temp_string. (By the way, you can replace that loop with a call to strcpy(), that does exactly that, except it will end only when it finds a '\0'.)
You might also want to read What's the rationale for null terminated strings?
Here is your Final Code:
#include<stdio.h>
#include<stdio.h>
#include<string.h>
int main()
{
char ch;
int i = 0, j = 0;
int length = 0;
int lengthsb = 0;
char string[100];
char temp_string[100];
printf(" Enter the string to divide\n ");
while(ch != '\n')
{
ch = getchar();
string[i] = ch;
i++;
}
string[i]=NULL;
printf("%s", string);
i = 0;
while(string[i] != '\0')
{
temp_string[i] = string[i];
i++;
}
temp_string[i]=NULL;
length = strlen(temp_string);
printf("Entered string is %s and its length is %d\n", temp_string, length);
}
In the above code what exactly you are missing is NULL or '\0' termination of the string. I just added it to make it useful.

Resources