i am writing a basic c program to display two strings, one taken from user i.e "a" and the other being defined in code "b" but when i run the code below string "a" gets appended to "b". why? and what is that symbol at end of "a"
updated code:
#include <stdio.h>
#include <string.h>
int main()
{
char a[ 5 ];
int i=0;
while(i<5)
{
a[i]=getchar();
i++;
}
char b[]={'r','f','s','/0'};
printf("output:-");
printf("\n %s",a);
printf("\n %s",b);
return 0;
console
qwert
output:-qwert$
rfs$qwert$
there is a some special symbol instead of $ above, what is it?
Putting all the comments into an answer. The problems in the original code stem mostly from not NUL terminating the character arrays to produce valid C strings.
a is not NUL terminated. Can fix by increasing the a array by 1 and explicitly writing a NUL to the last byte.
b is not NUL terminated. Can fix by initialising b using a literal string or a char array with '\0' as the last byte. The example below uses the former.
Here is the full code with the errors corrected. Note that the code to read input is fragile as it only accepts exactly a 5 character string.
#include <stdio.h>
#include <string.h>
int main(void)
{
char a[6];
int i=0;
while (i<5) {
a[i]=getchar();
i++;
}
a[i] = '\0';
char b[]="rfs";
printf("output:-\n");
printf(" %s\n",a);
printf(" %s\n",b);
return 0;
}
Related
Hello guys, i have this code:
#include <stdio.h>
int main()
{
int numberPosition=8;
char senha[1000]="01000hello";
printf("%i\n", numberPosition);
senha[numberPosition]="";
printf("\n%s\n", senha);
return 0;
}
When I executes my code my return is: 01000heo.
However if I delete the line "printf("%d\n", numberPosition);" my return is: 01000helo
Why printf deletes an element from my array?
senha[numberPosition]=""; is problematic as the left side is expecting a char but the right side is a char * which is then implicitly cast to an integer. This is often an error and gcc will generate a warning. Here is the explicit cast:
senha[numberPosition]=(unsigned long) "";
This will convert the address where the string "" is stored to an integer. It happens to evaluate to 8 which is backspace \b:
./a.out | od -a
0000000 8 nl nl 0 1 0 0 0 h e l bs o nl
0000016
what you want, what you really, really want is:
senha[numberPosition]='\0';
which will print:
8
01000hel
You clarified you wanted the output "01000helo" and either of these produce that output for me:
#include <stdio.h>
int main() {
int numberPosition=8;
char senha[1000]="01000hello";
senha[numberPosition] = 'o';
senha[numberPosition+1] = '\0';
printf("%s\n", senha);
}
or:
#include <stdio.h>
#include <string.h>
int main() {
int numberPosition=8;
char senha[1000]="01000hello";
strcpy(senha + numberPosition, "o");
printf("%s\n", senha);
}
It would be a good idea to add boundary checks.
Your comment below talks about removing characters which is a different problem that you initially described. You want to check out memmove() (which permit overlap of dst, src, unlike strcpy(), memcpy()).
This question already has answers here:
What is going on with 'gets(stdin)' on the site coderbyte?
(3 answers)
Closed 3 years ago.
I just want to reverse the string order by switching the place of each index in the string.
#include <stdio.h>
#include <string.h>
void FirstReverse(char str[]) {
int a = strlen(str);
for(int i=0; i<strlen(str) ;i++){
str[i] = str[a-1];
a-=1;
}
}
int main(void) {
// keep this function call here
FirstReverse(gets(stdin));
return 0;
}
Error: "signal: segmentation fault (core dumped)"
There are multiple errors in your code. The obvious ones are that gets is used wrong (and, to be honest, that it is used at all) and it does not output the result in any way. But let's apply some quick fixes with minimal changes to your logic:
#include <stdio.h>
#include <string.h>
void FirstReverse(char str[]) {
int a = strlen(str);
for(int i=0; i<strlen(str) ;i++){
str[i] = str[a-1];
a-=1;
}
}
int main(void) {
char string[100]; // This is going to be our working field where the changes happen
fgets(string, 100, stdin); // read a line of up to 100 characters into "string"
FirstReverse(string); // do the work (this could be chained, like it was originally)
puts(string); // output the result
return 0;
}
Now it compiles and executes without failing but the result is wrong:
In: My favourite string
Out: gnirts ette string
What went wrong? Let's follow what happens step by step:
i a
↓ ↓
My favourite string
(program writes the last character [see point 3 below] in place of `M`)
↓ ↓
y favourite string
(program writes `g` in place of `y`)
↓ ↓
g favourite string
(program writes `n` in place of the space)
↓ ↓
gnfavourite string
(program writes `i` in place of `f`)
etc.
ia
↓↓
gnirts eite string
(program writes `t` in place of `i`)
ai
↓↓
gnirts ette string
(program writes `t` in place of `t`)
a i
↓ ↓
gnirts ette string
(program writes `e` in place of `e`)
etc.
Three problems here:
By rewriting a character from the start by another from the end, you're not doing swapping. You're just copying the data from the end to start (but surely, in reverse order). The original is lost.
You are actually going twice through, because by the time i reaches half of the interval, a keeps decreasing and they cross. Now i still needs to finish the loop and a continues towards the beginning of the string where you've already been. If you actually did swapping, you'd swap 1 with 2 and then later 2 with 1 again, resulting in the original unchanged!
(minor) A string returned by (f)gets ends with a newline character, so that becomes the beginning of your result. Probably not what you want, but has an easy fix of chopping that off before feeding the string to your function.
You'll need to deal with each of these, other answers by now contain some advice. But I thought it instructive to run your code and try to "think like the machine" in explaining why the computer misunderstands your intention. If you swap the letters by copying one in a temporary variable, then rewriting str[i], then writing back in str[a-1] from the temporary, and stop before i and a cross each other, you can see for yourself you'll take care of 1 and 2.
run only till mid of the string
keep in some var the overridden char in side the loop
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
void FirstReverse(char str[]) {
int a = strlen(str);
for (int i = 0; i <= a; ++i, --a) {
char c = str[i];
str[i] = str[a - 1];
str[a - 1] = c;
}
}
int main(void) {
// keep this function call here
char s[100] = { 0 };
scanf("%s",s);
FirstReverse(s);
printf("%s",s);
return 0;
}
Simple way to do it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * reverse(char *str)
{
size_t size = strlen(str);
char *res = malloc(size * sizeof(char));
for(size_t i=0; i<size; i++) {
res[i] = str[size-i-1];
}
return res;
}
int main(void)
{
printf("%s\n",reverse("Hello World"));
return 0;
}
Output : dlroW olleH
Instead of switching each char, just create a new string in which you copy the last char, then the last-1 and so on. You'll also prevent yourself from switching the same char if the length of your string is uneven ('\0' put aside).
Here's my code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,j,n;
scanf("%d",&n);
n*=n;
char str[n];
for(i=0;i<n;i++){
str[i]='*';
}
printf("%s",str);
printf("\n%d",strlen(str));
return 0;
}
I input 2 and this is the output I got:
2
****ú#
7
In line 2 it has some weird characters that show in console (U+0013 or control-S between ú and #), but it didn't show here.
Could you explain this to me?
printf("%s", str) assumes that str points to a NUL-terminated char array (aka "C string"). str is not NUL terminated in your case, so printf is running off the end of the buffer, resulting in undefined behavior.
To fix this you need to do two things:
Allocate an additional byte for the NUL terminator
NUL-terminate the array when you're finished writing to it
char str[n+1]
for(i=0;i<n;i++){
str[i]='*';
}
str[n] = '\0';
You are printing with %s format specifier which expects a C string(char array with NUL character at the end). You need to make the last character \0 to make printf recognize the end of the string and stop printing. So allocate one more character in the array and set the last character to \0.
char str[n+1];
str[n] = '\0`;
You need to NUL-terminate your string, like so:
char str[n+1]; /// <<<
for(i=0;i<n;i++){
str[i]='*';
}
str[n]='\0'; /// <<<
I was trying to figure out that how a string with a known size can be filled with single characters. Then I wrote this simple code for a bigger problem that I have
(dynamic filling of a string with unknown size)
. When I tried to compile and run this code I encountered a problem which output had a heart symbol! and I don't know where it comes from.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
char str[3];
for(i=0;i<=2;i++){
str[i]=getc(stdin);
}
puts(str);
return 0;
}
Thank you.
The C strings are sequences of chars terminated by the null character (i.e. the character with code 0). It can be expressed as '\0', '\x0' or simply 0.
Your code fills str with three chars but fails to produce the null terminator. Accordingly, puts() prints whatever characters it finds in memory until it reaches the first null character.
Your code exposes Undefined Behaviour. It can do anything and it's not its fault.
In order to fix it you have to make sure the string ends with the null terminating character:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
// Make room for 3 useful chars and the null terminator
char str[4];
// Read three chars
for(i = 0; i < 3; i ++) {
str[i] = getc(stdin);
}
// Add the null terminator for strings
str[3] = 0;
puts(str);
return 0;
}
Update
As #JeremyP notes in a comment, if the file you read from (stdin) ends before the code reads 3 characters, fgetc() will return EOF (End Of File) characters that are also funny non-printable characters that makes you wonder where they came from.
The correct way to write this code is to check if the input file reached its EOF (feof()) before reading from it:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
// Make room for 3 useful chars and the null terminator
char str[4];
// Read at most three chars
for(i = 0; i < 3 && !feof(stdin); i ++) {
str[i] = getc(stdin);
}
// Add the null terminator for strings
str[i] = 0;
puts(str);
return 0;
}
Strings in c need to be null terminated so it could be that you forgot to add a '\0' character to the end of str. The reason the heart symbol shows up would be that when puts() tries to write out a string it keeps reading the next character in memory until it reaches a null terminator, '\0'. Since it doesn't encounter one it just continues reading into memory and happens to find the heart symbol I'd guess. Hope this helps.
The arrays [a] and [b] are supposed to take in 4 numbers each on two separate lines, and output ?A?B, as in the famous number guessing game. (For instance, 1234\n1347 should output 1A2B.) However, I found out that the 1 at a[0] gets replaced by \0 while the others are still fine. (Side-note: This happened on XCode, but not on Visual Studio.)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char a[4], b[4];
int i, j;
int A = 0, B = 0;
scanf("%s%s",a,b);
for(i=0;i<4;i++)
if(a[i] == b[i])
A++;
for(i=0;i<4;i++)
for(j=0;j<4;j++)
if(a[i] == b[j])
B++;
B = B-A;
printf("%dA%dB\n",A,B);
return 0;
}
Changing the arrays to size [5] solves the problem, but I want to understand what's going on. Thanks!
Strings in C are really called null terminated byte strings. That name gives a hint that there is a special terminator for the strings, which is the '\0' character.
A string of four characters needs space for five characters, with the fifth being the null terminator.
When you input four characters with your scanf call, the function will write the fifth (the terminator) out of bounds. And writing out of bounds leads to undefined behavior.