Odd printf behaviour [duplicate] - c

This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Returning an array using C
(8 answers)
Closed 3 years ago.
I have implemented my own strchr() function in C.
When calling the function and saving the output into a pointer I go ahead and print the stream of chars and the result looks fine. However, after calling a printf(), my stream of chars gets cut off for some reason. Does anyone understand why?
Here is my code:
#include <stdio.h>
#include <string.h>
char *mon_strchr(const char *chaine, int car)
{
int j = 0, i;
char *pbuff, buff[256];
pbuff = buff;
for (i = 0; chaine[i] != '\0'; i++)
{
if ((int)chaine[i] == car)
break;
i++;
}
for (i; chaine[i] != '\0'; i++)
{
buff[j] = chaine[i];
j++;
}
return pbuff;
}
int main()
{
const char str[] = "http://www.tutorialspoint.com";
const char ch = '.';
char *ret;
ret = mon_strchr(str, ch);
printf("%s\n", ret);
printf("String after |%c| is\n", ch);
printf("%s\n", ret);
return (0);
}
And this is the output:
.tutorialspoint.com
String after |.| is
.tutoria

Related

Unexpected result after printing a string in c [duplicate]

This question already has answers here:
Why does fgetc() return int instead of char?
(2 answers)
Closed 1 year ago.
The code is -
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *filevar;
filevar = fopen("file", "r");
char copy [100];
int i = 0;
while(1)
{
char ch = fgetc(filevar);
if(ch==EOF)
{
break;
}
copy[i] = ch;
i++;
}
printf("\n%s", copy);
fclose(filevar);
return 0;
}
When I run it the out put I get is
textblablaâ– a
file content is -
textblabla
Changing the file content changes the random charecters at end
Two main issues.
ch has to be int
You do not null character terminate the string
int ch = fgetc(filevar);
if(ch==EOF)
{
copy[i] = 0;
break;
}
copy[i] = ch;
i++;

How to return a pointer to a string in C [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I tried to develop a function which take a string reverse letters and return pointer to string.
char *reverseStr(char s[])
{
printf("Initial string is: %s\n", s);
int cCounter = 0;
char *result = malloc(20);
while(*s != '\0')
{
cCounter++;
s++;
}
printf("String contains %d symbols\n", cCounter);
int begin = cCounter;
for(; cCounter >= 0; cCounter--)
{
result[begin - cCounter] = *s;
s--;
}
result[13] = '\0';
return result;
}
in main function I invoke the function and tried to print the result in this way:
int main()
{
char testStr[] = "Hello world!";
char *pTestStr;
puts("----------------------------------");
puts("Input a string:");
pTestStr = reverseStr(testStr);
printf("%s\n", pTestStr);
free(pTestStr);
return 0;
}
but the result is unexpected, there is no reverse string.
What is my fault?
There are multiple mistakes in the shared code, primarily -
s++; move the pointer till '\0'. It should be brought back 1 unit to
point to actual string by putting s--. Other wise the copied one will start with '\0' that will make it empty string.
Magic numbers 20 and 13. where in malloc() 1 + length of s should be
sufficient instead or 20. For 13 just move a unit ahead and put '\0'
However, using string.h library functions() this can be super easy. But I think you are doing it for learning purpose.
Therefore, Corrected code without using string.h lib function() should look like this:
char *reverseStr(char s[])
{
printf("Initial string is: %s\n", s);
int cCounter = 0;
while(*s != '\0')
{
cCounter++;
s++;
}
s--; //move pointer back to point actual string's last charecter
printf("String contains %d symbols\n", cCounter);
char *result = (char *) malloc(sizeof(char) * ( cCounter + 1 ));
if( result == NULL ) /*Check for failure. */
{
puts( "Can't allocate memory!" );
exit( 0 );
}
char *tempResult = result;
for (int begin = 0; begin < cCounter; begin++)
{
*tempResult = *s;
s--; tempResult++;
}
*tempResult = '\0';
//result[cCounter+1] = '\0';
return result;
}
Calling from main
int main()
{
char testStr[] = "Hello world!";
char *pTestStr;
puts("----------------------------------");
puts("Input a string:");
pTestStr = reverseStr(testStr);
printf("%s\n", pTestStr);
free(pTestStr);
}
Output
----------------------------------
Input a string:
Initial string is: Hello world!
String contains 12 symbols
!dlrow olleH
As per WhozCraig suggestion just by using pointer arithmetic only -
char *reverseStr(const char s[])
{
const char *end = s;
while (*end)
++end;
char *result = malloc((end - s) + 1), *beg = result;
if (result == NULL)
{
perror("Failed to allocate string buffer");
exit(EXIT_FAILURE);
}
while (end != s)
*beg++ = *--end;
*beg = 0;
return result;
}
Your code can be simplified using a string library function found in string.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *reverseStr(char s[])
{
printf("Initial string is: %s\n", s);
int cCounter = strlen(s);
char *result = malloc(cCounter + 1);
printf("String contains %d symbols\n", cCounter);
int begin = cCounter;
for(; cCounter > 0; cCounter--)
{
result[begin - cCounter] = s[cCounter - 1];
}
result[begin] = '\0';
return result;
}
int main()
{
char testStr[] = "Hello world!";
char *pTestStr;
puts("----------------------------------");
puts("Input a string:");
pTestStr = reverseStr(testStr);
printf("%s\n", pTestStr);
free(pTestStr);
return 0;
}
Output:
----------------------------------
Input a string:
Initial string is: Hello world!
String contains 12 symbols
!dlrow olleH

I need to read a file until "over" is encountered [duplicate]

This question already has an answer here:
C: How to compare two strings? [duplicate]
(1 answer)
Closed 9 years ago.
I have trouble reading a file until a word is encountered, this is what I have done but I don't think the if statement allows strings to be written within them
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
int i;
char buffer[100];
FILE *fptr = fopen("testing.txt", "r");
if(fptr != NULL)
printf("file opened successfully\n");
else {
printf("file error occured\n");
printf("terminating program...\n");
return 0;
}
while (fgets(buffer, 100,fptr))
{
if(buffer != "over") {
printf("%s ", buffer);
}
else
return 0;
}
}
When you do
if(buffer != "over")
you compare two pointers, the pointer to buffer and the pointer to the string literal "over". Those pointers will never be the same.
To compare strings in C you have to use the strcmp function.
For comparing string you need to use strcmp() function. You can't do directly by if(buffer != "over"). It compares pointers instead of stings.
#include <stdio.h>
#include <string.h>
int isEndWith(const char *string, const char *word){
int len = strlen(string);
int lenw = strlen(word);
if(len >= lenw)
return strncmp(string + len - lenw, word, lenw)==0;//or use strcmp
else
return 0;
}
int main(void){
char str1[] = "how are you over i am busy over\n";
char str2[] = "how are you over i am busy over\n";
char *p;
if(p=strchr(str1, '\n'))
*p = '\0';//chomp \n
if(!isEndWith(str1, "over"))//check case end string
printf("%s", str1);
else {
int len = strlen(str1);
str1[len - 4] = '\0';// 4 : strlen("over");
printf("%s\n", str1);//print "how are you over i am busy \n"
}
if(p=strstr(str2, "over"))//check case contain string
*p = '\0';
printf("%s\n", str2);//print "how are you \n"
return 0;
}

strtok not working in call function [duplicate]

This question already has answers here:
strtok behavior
(2 answers)
Closed 9 years ago.
strtok() is crashing. It works in main(), but not in the call function.
Please advise me. Thank you.
int checkNumberOfTokens (char* text, char* delimitChar) {
int numberOfTokens = 0;
char *t;
int i;
printf("Text: %s\n", text);
printf("delimitChar: %s\n", delimitChar);
t = strtok(text, delimitChar);
for (i=0; t != NULL; i++) {
printf("token %d is \"%s\"\n", i, t);
t = strtok(NULL, delimitChar);
}
numberOfTokens = i;
printf("Total number of tokens: %d\n", numberOfTokens);
return numberOfTokens;
}
int main()
char* transitionTable[] = {
"NA, NA, NA, NA, NA, NA",
"defaultStart, elseOther, 1, 2, 6, NA",
};
printf("%s \n", transitionTable[1]);
char delimitChar[] = ",";
checkNumberOfTokens (transitionTable[1], delimitChar);
strtok input string has to be writable as strtok modifies the input string. But you are passing a string literal and string literals are non modifiable.
See c-faq on string literals:
http://c-faq.com/decl/strlitinit.html
PROBLEM: You're passing in a string literal (read-only); but strtok() expects to be able to modify the string.
SUGGESTION: try strchr() instead of strtok().
EXAMPLE:
#include <stdio.h>
#include <string.h>
int
checkNumberOfTokens (char * text, char delimitChar)
{
char *s = text;
int ct = 1;
if ((s == NULL) || (strlen(s) == 0))
return 0;
while ((s = strchr(s, delimitChar))) {
s++;
ct++;
}
return ct;
}
int main(int argc, char *argv[])
{
int ct = checkNumberOfTokens("ABC,DEF,GEHI", ',');
printf ("ct=%d\n", ct);
return 0;
}

How can I read a string in c? [duplicate]

This question already has answers here:
How to read string from keyboard using C?
(6 answers)
Closed 9 years ago.
I use this code, but it's not working.
#include <stdio.h>
#include <string.h>
int main() {
char c, *strx = 0;
c = getchar();
while(c != '\n') {
strx = strcat(strx, &c);
c = getchar();
}
printf("%s\n", *strx);
return 0;
}
How can I put a word into a string?
Change
char *strx = 0
to
char strx [256];
For example:
#include <stdio.h>
#include <string.h>
int main()
{
char c, strx[256] = "";
int i = 0;
c = getchar();
while (c != '\n') {
strx[i++] = c;
c = getchar();
}
printf("%s\n", strx);
return 0;
}
You need to allocate space for strx (here on the stack, you can also you malloc)
#include <stdio.h>
#include <string.h>
int main()
{
char c, strx[100] = "";
int i = 0;
c = getchar();
while (c != '\n') {
strx[i++] = c;
if (i == 99)
break;
c = getchar();
}
strx[i] = '\0';
printf("%s\n", strx);
return 0;
}
strcat doesn't work because it expects a null char at the end but it will probably find garbage after the char.
More simply, you can use scanf:
#include <stdio.h>
#include <string.h>
int main()
{
char strx[100] = "";
scanf("%99s", strx);
printf("%s\n", strx);
return 0;
}

Resources