Printf writing extra character on occasion - c

this is the code, it is supposed to invert a string.
#include <stdio.h>
void StrRev(char str[]) {
int len=strlen(str);
char out[len];
int i;
for(i=0;i<len;i++){
out[i]=str[len-i-1];
}
printf("%s",out);
}
int main(void) {
StrRev("TestString");
return 0;
}
expected output:
gnirtStseT
actual output:
gnirtStseT#
the same thing happens with other inputs, while not on some others.
compiled with MingW on Code::Blocks

Two issues:
You fail to #include <string.h>, so there's no declaration for strlen. So the function is implicitly declared as int strlen(). So add that to the top of the file.
You also aren't adding the null terminating character to your reversed string.
After the for loop, set one additional character in the array to 0. Also, you'll need to make the array one larger to fit it.
#include <stdio.h>
// import declaration of strlen
#include <string.h>
void StrRev(char str[]) {
int len=strlen(str);
char out[len+1]; // increase length to make room for null terminator
int i;
for(i=0;i<len;i++){
out[i]=str[len-i-1];
}
out[i]=0; // add null terminator
printf("%s",out);
}
int main(void) {
StrRev("TestString");
return 0;
}

strlen() returns the length of the string without the null terminator at the end. So when you're copying over the characters, you're skipping the NULL at the end. If you simply use
int len=strlen(str) + 1;
instead of
int len=strlen(str);
Then everything should work.

Related

Using string as parameter for function

I am trying to use a function with a string as a parameter. I am running into a couple of error messages. First, it says that string[i] is not an array, pointer, or vector, despite the fact that string is a character array. Secondly, it says that I am doing a pointer to integer conversion. Here is my code:
#include <stdio.h>
#include <string.h>
void example (char string) {
int i;
for (i = 0; i < strlen(string); i++) {
printf (string[i]);
}
}
int main (void) {
example("I like pie");
return 0;
}
void example(char string) should be void example(char *string). You declared it to take a character, you want it to take a character pointer or array.
Also, you need to tell printf you are giving it a character: printf("%c", string[i]);.
Your API is wrong it should be
void example (char *string) { // string is a pointer
int i;
size_t n = strlen(string);
for (i = 0; i < n; i++) {
printf ("%c",string[i]); // print character using %c
}
}
Calculate the string length before the loop , calling strlen() in each iteration is not a good idea.
PS: what string points to is read-only you can't modify it
You should use void example(char *string) instead of void example (char string).
#include <stdio.h>
#include <string.h>
void example (char *string) {
int i;
for (i = 0; i < strlen(string); i++) {
printf ("%c",string[i]);
}
printf("\n");
}
int main (void) {
example("I like pie");
return 0;
}
Your function example just receives a character. To get a string you can use a pointer. Also you can use "%s" format specifier in printf instead of using the for loop and strlen() function.
#include <stdio.h>
#include <string.h>
void example (char *string) {
int i;
printf ("%s\n",string);
}

check if a char exists in a char 2 dimensional array

I'm trying to check if a character belongs to a two dimensional array of characters, but my code doesn't work right for all characters. I think that something goes wrong with my pointer.For example if i change 'b' to 'r' it doesn't work correctly.
Thanks in advance.
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char *pch;
char matrix[2][2]={
"best","cover",
"orbit","boost"
};
pch=strchr(matrix,'b');
if (pch==NULL)
{
printf ("not exists");
}
else
{
printf("exists");
}
return 0;
}
There are three problems in your code.
You need to include <stdio.h> in order to use printf.
There isn't enough memory allocated here:
char matrix[2][2]={
"best","cover",
"orbit","boost"
};
You give space for two strings each of which can hold 1 character(+1 for the NUL-terminator at the end).
Fix it by using:
char matrix[4][6]={
"best","cover",
"orbit","boost"
};
The six is the maximum number of characters in a string + one for the \0 at the end and the four is the number of maximum number of strings in the 2D array.
strchr expects the first argument to be of type const char*. You give the argument matrix which is of type char(*)[2]. You need to loop and find if the character is in each string of the array of array of chars.
After fixing these problems, your code will be:
#include <stdlib.h> // Not required
#include <string.h> // For strchr()
#include <stdio.h> // For printf()
int main(int argc, char *argv[]) {
char *pch;
char matrix[4][6]={
"best","cover",
"orbit","boost"
};
int i;
for(i=0;i<4;i++)
{
pch=strchr(matrix[i],'b');
if (pch==NULL)
{
printf ("not exists in %s\n",matrix[i]);
}
else
{
printf("exists in %s\n",matrix[i]);
}
}
return 0;
}

Own version of strncpy shouldn't work, but it does

so here's the code.
#include <stdio.h>
#define MAXOUTPUT 10
void copy_n(char des[], char src[], int n);
int main(void)
{
int i;
char output[MAXOUTPUT];
copy_n(output, "SomeTestInputHere", 26);
printf("%s\n", output);
for(i=0;output[i]!='\0';i++)
printf("%c\n", output[i]);
return 0;
}
void copy_n(char des[], char src[], int n)
{
int i;
for(i=0;i<MAXOUTPUT;i++)
{
if(i<n)
des[i]=src[i];
else
des[i]='\0';
}
}
Why won't it crush when printing a string or char by char? Where does the terminating NUL come from here?
It's for Reek's Pointers on C, and is supposed to copy n characters, filling with NUL when, des>=src.But when src>des it should copy all chars without terminating NUL.
Your copy_n function for loop uses the constant MAXOUTPUT as the guard in the loop; and MAXOUTPUT has a value 10.

Iterating over C string not working

First, my objective with this code: take in a sentence into a C string. Iterate through the sentence and see how many instances of a particular letter occur.
This code is working somewhat but not giving the right number? Not sure why:
#include <stdio.h>
#include <string.h>
int tracker=0;
int letterCount (char *sentence)
{
int s=strlen(sentence);
int i=0;
for (i=0; i<s; i++){
if (sentence[i]=='h') {
tracker++;
}
}
return tracker;
}
int main(int argc, const char * argv[])
{
char *string="Hi there, what's going on? How's it going?";
letterCount(string);
printf("this sentensce has %i H's", tracker);
return 0;
}
The output I'm getting:
this sentensce has 2 H's
Not quite right. Any ideas?
This is the correct code if you mean case insensitive H:
#include <stdio.h>
#include <string.h>
int tracker=0;
int letterCount (char *sentence)
{
int s=strlen(sentence);
int i=0;
for (i=0; i<s; i++){
if (sentence[i]=='h' || sentence[i]=='H') { //'h' is not the same as 'H'
tracker++;
}
}
return tracker;
}
int main(int argc, const char * argv[])
{
char *string="Hi there, what's going on? How's it going?";
letterCount(string);
printf("this sentensce has %i H's", tracker);
return 0;
}
You have just mispelled small and the capital letter in your code.
Remember, the C language is case sensitive!
Although your label talks about the number of Hs, your letterCount looks for hs instead -- and it looks to me like the input you've provided does have two instances of lower-case h, just as it says.
If you want to count them together, you might consider filtering each input with tolower or toupper before checking what you have.
That number looks correct to me: you have 2 'h' characters in that sentence. If you want to count the 'H' characters as well, then you need a separate check.
size_t letterCount(const char* sentence, char c)
{
size_t count = 0;
while(sentence)
{
count += (*sentence == c);
++sentence;
}
return count;
}
What do we see here?
You can't have negative count, so use an unsigned type like size_t
sentence shouldn't be modified, so it should be const
pass in the char you want to match
sentence is a pointer, if it is null you are done. Don't need to call strlen.
sentence is a pointer, the actual pointer is pass by value, so you can modify it (see the increment, no need to make an extra variable)
boolean operators return 1 or 0, so no need to use the if. (Although, I haven't looked at the assembly to see if an if branch or an add 0 is cheaper. YMMV)

passing of strings in C function

i have the following problems in C programming.
I have an array of strings stored as words[10][50]. I want to extract each of the string from the array and then pass it on to another function. I tried on the following:
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
int Check_Anagram(char*,char*);
void main()
{
char words[10][20];
int i;
int flag;
for(i=0;i<3;i++)
{
scanf("%s\n",words[i][20]);
}
for(i=1;i<10;i++)
{
flag = Check_Anagram(words[i][20],words[i-1][20]);
}
getch();
}
int Check_Anagram(char *a,char *b)
{
printf("%s %s\n",a,b);
return 1;
}
This creates an exception during compiling.
Now i think that when i use the "printf" statement then this nomenclature works fine i.i words[i] prints the string "i" from the double dimension words array. When i try to do the same thing with the check function then the error occurs.
Can soemone point me how to do this passing ?
P.S. Please ignore any error in efficiency of program and likewise. I need your help and this is just a test program at learning string passing to a function
Thanks
You're passing words[i][20]. You need to pass words[i] instead in both loops. Try this:
for(i = 1; i < 3; i++) /* i < 3 */
{
flag = Check_Anagram(words[i], words[i-1]);
}
Another problem is that you're reading 3 strings and trying to print 10. So when you pass words[3] it contains garbage: printf tries to print garbage which need not be 0-terminated.
In the first for loop, when i is 0, you're pointing to words[-1], that's your exception.
flag = Check_Anagram(words[i][20],words[i-1][20]);
You are passing the 21st letter of each word the Check_Anagram. Instead you should pass the words themselves:
flag = Check_Anagram(words[i],words[i-1]);
You have a similar problem where you use scanf. To read a line from the console to each word you would use:
for(i=0;i<10;i++)
{
scanf("%s\n",words[i]);
}
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
int Check_Anagram(char [],char []);
void main()
{
char words[10][20];
int i;
int flag;
for(i=0;i<3;i++)
{
scanf("%s\n",words[i]);
}
for(i=1;i<10;i++)
{
flag = Check_Anagram(words[i],words[i-1]);
}
getch();
}
int Check_Anagram(char a[],char b[])
{
printf("%s %s\n",a,b);
return 1;
}
I finally got it corrected thanks to the help of all users.
I have posted the corrected code for people who are struggling with passing of string extracted from an array of strings to another function. hope it helps.

Resources