I', learning C and I'm getting no output for some reason, probably I don't return as I should but how I should? (described the problem in the comments below :D)
Any help is appreciated!
#include <stdio.h>
#include <ctype.h>
#include <string.h>
char *makeUpperCase (char *string);
int main()
{
printf(makeUpperCase("hello")); //Here there is no output, and when I'm trying with the format %s it returns null
return 0;
}
char *makeUpperCase(char *string)
{
char str_out[strlen(string) + 1];
for (int i = 0; i < strlen(string); ++i)
str_out[i] = toupper(string[i]);
printf(str_out); //Here I get the output.
return str_out;
}
You declared within the function a local variable length array that will not be alive after exiting the function
char str_out[strlen(string) + 1];
So your program has undefined behavior.
If the function parameter declared without the qualifier const then it means that the function changes the passed string in place. Such a function can be defined the following way
char * makeUpperCase( char *string )
{
for ( char *p = string; *p != '\0'; ++p )
{
*p = toupper( ( unsigned char )*p );
}
return string;
}
Otherwise you need to allocate dynamically a new string. For example
char * makeUpperCase( const char *string )
{
char *str_out = malloc( strlen( string ) + 1 );
if ( str_out != NULL )
{
char *p = str_out;
for ( ; *string != '\0'; ++string )
{
*p++ = toupper( ( unsigned char )*string );
}
*p = '\0';
}
return str_out;
}
Here is a demonstration program.
#include <stdop.h>
#include <stdlib.h>
#include <string.h>
char *makeUpperCase( const char *string )
{
char *str_out = malloc( strlen( string ) + 1 );
if (str_out != NULL)
{
char *p = str_out;
for (; *string != '\0'; ++string)
{
*p++ = toupper( ( unsigned char )*string );
}
*p = '\0';
}
return str_out;
}
int main( void )
{
char *p = makeUpperCase( "hello" );
puts( p );
free( p );
}
The program output is
HELLO
The problem is that printf() is buffering output based on a bit complex mechanism. When you are outputting to a terminal, printf() just buffers everything until the buffer fills (which is not going to happen with just the string "hello", or until it receives a '\n' character (which you have not used in your statement)
So, to force a buffer flush, just add the following statement
fflush(stdout);
after your printf() call.
Related
I have to make a function, that will code my sentence like this: I want to code all words with an o, so for example I love ice cream becomes I **** ice cream.
But my function ignores the result of strchr. And I don't know why.
This is my code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define LEN 1000
char *Shift(char *str, char *let) {
const char *limits = " ,-;+.";
char copy[LEN];
strcpy(copy, str);
char *p;
char *ptr;
ptr = strtok(copy, limits);
for (int j = 0; ptr != NULL; ptr = strtok(NULL, limits), ++j) {
int len = 0;
if (strchr(ptr, let) != NULL) {
p = strstr(str, ptr);
for (int i = 0; i < strlen(ptr); i++) {
p[i] = "*";
}
}
}
return str;
}
int main() {
char *s = Shift("I love my cocktail", "o");
puts(s);
}
Expected output is: I **** my ********
but I've got just printed the original string
For starters the function strchr is declared like
char *strchr(const char *s, int c);
that is its second parameter has the type int and the expected argument must represent a character. While you are calling the function passing an object of the type char * that results in undefined behavior
if (strchr(ptr, let) != NULL) {
It seems you mean
if (strchr(ptr, *let) != NULL) {
Also you may not change a string literal. Any attempt to change a string literal results in undefined behavior and this code snippet
p = strstr(str, ptr);
for (int i = 0; i < strlen(ptr); i++) {
p[i] = "*";
}
tries to change the string literal passed to the function
char *s = Shift("I love my cocktail", "o");
And moreover in this statement
p[i] = "*";
you are trying to assign a pointer of the type char * to a character. At least you should write
p[i] = '*';
If you want to change an original string you need to store it in an array and pass to the function the array instead of a string literal. For example
char s[] = "I love my cocktail";
puts( Shift( s, "o" ) );
Pay attention to that there is no great sense to declare the second parameter as having the type char *. Declare its type as char.
Also the function name Shift is confusing. You could name it for example like Hide or something else.
Here is a demonstration program.
#include <stdio.h>
#include <string.h>
char * Hide( char *s, char c )
{
const char *delim = " ,-;+.";
for ( char *p = s += strspn( s, delim ); *p; p += strspn( p, delim ) )
{
char *q = p;
p += strcspn( p, delim );
char *tmp = q;
while ( tmp != p && *tmp != c ) ++tmp;
if ( tmp != p )
{
for ( ; q != p; ++q ) *q = '*';
}
}
return s;
}
int main( void )
{
char s[] = "I love my cocktail";
puts(s);
puts( Hide( s, 'o' ) );
}
The program output is
I love my cocktail
I **** my ********
The for loop
for ( ; q != p; ++q ) *q = '*';
within the function can be rewritten as a call of memset
memset( q, '*', p - q );
There are multiple problems:
copying the string to a fixed length local array char copy[LEN] will cause undefined behavior if the string is longer than LEN-1. You should allocate memory from the heap instead.
you work on a copy of the string to use strtok to split the words, but you do not use the correct method to identify the parts of the original string to patch.
you should pass a character to strchr(), not a string.
patching the string with p[i] = "*" does not work: the address of the string literal "*" is converted to a char and stored into p[i]... this conversion is meaningless: you should use p[i] = '*' instead.
attempting to modify a string literal has undefined behavior anyway. You should define a modifiable array in main and pass the to Shift.
Here is a corrected version:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *Shift(char *str, char letter) {
const char *limits = " ,-;+.";
char *copy = strdup(str);
char *ptr = strtok(copy, limits);
while (ptr != NULL) {
if (strchr(ptr, letter)) {
while (*ptr != '\0') {
str[ptr - copy] = '*';
ptr++;
}
}
ptr = strtok(NULL, limits);
}
free(copy);
return str;
}
int main() {
char s[] = "I love my cocktail";
puts(Shift(s, 'o'));
return 0;
}
The above code still has undefined behavior if the memory cannot be allocated. Here is a modified version that operates in place to avoid this problem:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
char *Shift(char *str, char letter) {
char *ptr = str;
while ((ptr = strchr(ptr, letter)) != NULL) {
char *p = ptr;
while (p > str && isalpha((unsigned char)p[-1]))
*--p = '*';
while (isalpha((unsigned char)*ptr)
*ptr++ = '*';
}
return str;
}
int main() {
char s[] = "I love my cocktail";
puts(Shift(s, 'o'));
return 0;
}
Note that you can also search for multiple characters at a time use strcspn():
#include <ctype.h>
#include <stdio.h>
#include <string.h>
char *Shift(char *str, const char *letters) {
char *ptr = str;
while (*(ptr += strcspn(ptr, letters)) != '\0') {
char *p = str;
while (p > str && isalpha((unsigned char)p[-1]))
*--p = '*';
while (isalpha((unsigned char)*ptr)
*ptr++ = '*';
}
return str;
}
int main() {
char s[] = "I love my Xtabentun cocktail";
puts(Shift(s, "oOxX"));
return 0;
}
I'm trying to write a function that will print out a substring of string however when printing it, only the first character in the array is printed.
As you can see in the code I've put a printf statement in the function after the substring is created and it displays properly. However when the function is passed into a printf function in the main function it only prints the first character.
Thanks for any help people are able to provide.
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
char *ft_substr (const char *s, unsigned int start, size_t len)
{
char *str;
unsigned int i;
unsigned int j;
str = malloc(len * sizeof(char) + 1);
i = start;
j = 0;
while (i < len + start)
{
str[j] = s[i];
j++;
i++;
}
str[j + 1] = '\0';
printf("%s\n", str);
free(str);
return (str);
}
int main (void)
{
char hello[] = "Hello World";
char sub = *ft_substr(hello, 1, 4);
printf("%s\n", &sub);
return (0);
}
Before returning the pointer str from the function you freed all the allocated memory
free(str);
return (str);
So the returned pointer is invalid.
Remove the statement
free(str);
Another problem in the function is using an incorrect index in this statement
str[j + 1] = '\0';
Just write
str[j] = '\0';
Also this declaration is incorrect
char sub = *ft_substr(hello, 1, 4);
It declares a single character while you need to declare a pointer that will point to the dynamically allocated string in the function. So write
char *sub = ft_substr(hello, 1, 4);
and then write
printf("%s\n", sub);
free( sub );
And if you are using the type size_t for the length of a string then use indices also of the type size_t.
Here is a demonstrative program.
#include <stdio.h>
#include <stdlib.h>
char * ft_substr( const char *s, size_t start, size_t len )
{
char *str = malloc( len + 1 );
if ( str != NULL )
{
size_t i = 0;
for ( ; i < len; i++ )
{
str[i] = s[start + i];
}
str[i] = '\0';
}
return str;
}
int main(void)
{
const char *hello= "Hello World";
char *sub = ft_substr( hello, 1, 4 );
if ( sub != NULL ) puts( sub );
free( sub );
return 0;
}
Its output is
ello
The function will be more safer if it will check whether the starting index and the length are specified correctly. For example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * ft_substr( const char *s, size_t start, size_t len )
{
char *str = NULL;
size_t n = strlen( s );
if ( start < n )
{
if ( n - start < len ) len = n - start;
str = malloc( len + 1 );
if ( str )
{
memcpy( str, s + start, len );
str[len] = '\0';
}
}
return str;
}
int main(void)
{
const char *hello= "Hello World";
char *sub = ft_substr( hello, 1, 4 );
if ( sub != NULL ) puts( sub );
free( sub );
return 0;
}
You have UB in your main. Yout try to print as string a single character (passed as reference).
int main (void)
{
char hello[] = "Hello World";
char *sub = ft_substr(hello, 1, 4);
printf("%s\n", sub?sub:"");
free(sub);
return (0);
}
I've been tryring to solve this problem for hours now.
void replaceLetters(char *text, char original, char new_char)
{
text = "Randoi";
for(int i = 0; i != '\0'; i++){
if(text[i] == original){
text[i] = new_char;
}
}
if I print out text in this function it's correct, but in the other function where this function is called the text doesn't change and i know there's something wrong with my pointers.
Please give me a hint. Tanks a lot.
Please see my code.
#include <stdio.h>
void replaceLetters(char *text, char original, char new_char)
{
for(int i = 0; text[i] != '\0'; i++)
{
if(text[i] == original)
{
text[i] = new_char;
}
}
}
int main()
{
char text[] = "Randoi";
replaceLetters(text,'n','T');
printf(text);
return 0;
}
The condition of for loop is "for(int i = 0; text[i] != '\0'; i++)"
Your function definition does not make a sense at least because you overwrote the first parameter
text = "Randoi";
with the address of a string literal and the condition in the for loop
for(int i = 0; i != '\0'; i++){
is incorrect. That is the for loop never will make iterations.
You should not use the type int for the index and the function should return the result string.
The function can be declared and defined the following way
char * replaceLetters(char *text, char original, char new_char)
{
for ( char *p = text; *p; ++p )
{
if ( *p == original ) *p = new_char;
}
return text;
}
Pay attention to that you may not use the function to change a string literal. Any attempt to change a string literal results in undefined behavior.
Here is a demonstrative progran.
#include <stdio.h>
char * replaceLetters(char *text, char original, char new_char)
{
for ( char *p = text; *p; ++p )
{
if ( *p == original ) *p = new_char;
}
return text;
}
int main(void)
{
char s[] = "character";
puts( s );
puts( replaceLetters( s, 'a', 'A' ) );
return 0;
}
The program output is
character
chArActer
I am new to pointers and want to learn them well. So this is my own attempt to write my strcat function. If I return just a it prints some binary things (I think it should print the solution), If I return *a it says seg fault core dumped I couldn't find the error. Any help is accepted thanks.
#include <stdio.h>
#include <string.h>
int main() {
char *strcaT();
char *a = "first";
char *b = "second";
printf("%s", strcaT(a, b));
return 0;
}
char *strcaT(char *t, char *s) {
char buffer[strlen(t) + strlen(s) - 1];
char *a = &buffer[0];
for (int i = 0; i < strlen(s) + strlen(t); i++, t++) {
if (*t == '\n') {
for (int i = 0; i < strlen(s);i++) {
buffer[strlen(t) + i] = *(s + i);
}
}
buffer[i] = *(t + i);
}
return a;
}
The code has multiple cases of undefined behavior:
you return the address of a local array in strcaT with automatic storage, which means this array can no longer be used once it goes out of scope, ie: when you return from the function.
the buffer size is too small, it should be the sum of the lengths plus 1 for the null terminator. You write beyond the end of this local array, potentially overwriting some important information such as the caller's framce pointer or the return address. This undefined behavior has a high chance of causing a segmentation fault.
you copy strlen(t)+strlen(s) bytes from the first string, accessing beyond the end of t.
It is unclear why you test for '\n' and copy the second string at the position of the newline in the first string. Strings do not end with a newline, they may contain a newline but and at a null terminator (byte value '\0' or simply 0). Strings read by fgets() may have a trailing newline just before the null terminator, but not all strings do. In your loop, the effect of copying the second string is immediately cancelled as you continue copying the bytes from the first string, even beyond its null terminator. You should perform these loops separately, first copying from t, then from s, regardless of whether either string contains newlines.
Also note that it is very bad style to declare strcaT() locally in main(), without even a proper prototype. Declare this function before the main function with its argument list.
Here is a modified version that allocates the concatenated string:
#include <stdio.h>
#include <stdlib.h>
char *strcaT(const char *s1, const char *s2);
int main() {
const char *a = "first";
const char *b = "second";
char *s = strcaT(a, b);
if (s) {
printf("%s\n", s);
free(s);
}
return 0;
}
char *strcaT(const char *t, const char *s) {
char *dest = malloc(strlen(t) + strlen(s) + 1);
if (dest) {
char *p = dest;
/* copy the first string */
while (*t) {
*p++ = *t++;
}
/* copy the second string at the end */
while (*s) {
*p++ = *s++;
}
*p = '\0'; /* set the null terminator */
}
return dest;
}
Note however that this is not what the strcat function does: it copies the second string at the end of the first string, so there must be enough space after the end of the first string in its array for the second string to fit including the null terminator. The definitions for a and b in main() would be inappropriate for these semantics, you must make a an array, large enough to accommodate both strings.
Here is a modified version with this approach:
#include <stdio.h>
char *strcaT(char *s1, const char *s2);
int main() {
char a[12] = "first";
const char *b = "second";
printf("%s\n", strcaT(a, b));
return 0;
}
char *strcaT(char *t, const char *s) {
char *p = t;
/* find the end of the first string */
while (*p) {
*p++;
}
/* copy the second string at the end */
while (*s) {
*p++ = *s++;
}
*p = '\0'; /* set the null terminator */
return t;
}
It is a very bad idea to return some local variable, it will be cleared after the function finishes its operation. The following function should work.
char* strcaT(char *t, char *s)
{
char *res = (char*) malloc(sizeof(char) * (strlen(t) + strlen(s) + 1));
int count = 0;
for (int i = 0; t[i] != '\0'; i++, count++)
res[count] = t[i];
for (int i = 0; s[i] != '\0'; i++, count++)
res[count] = s[i];
res[count] = '\0';
return res;
}
In the main function
char *strcaT();
It should be declared before main function:
char *strcaT(char *t, char *s);
int main() {...}
You returns the local array buffer[], it's is undefined behavior, because out of strcaT function, it maybe does not exist. You should use the pointer then allocate for it.
The size of your buffer should be +1 not -1 as you did in your code.
char *strcaT(char *t, char *s) {
char *a = malloc(strlen(t) + strlen(s) + 1);
if (!a) {
return NULL;
}
int i;
for(i = 0; t[i] != '\0'; i++) {
a[i] = t[i];
}
for(int j = 0; s[j] != '\0'; j++,i++) {
a[i] = s[j];
}
a[i] = '\0';
return a;
}
The complete code for test:
#include <stdio.h>
#include <stdlib.h>
char *strcaT(char *t, char *s);
int main() {
char *a = "first";
char *b = "second";
char *str = strcaT(a, b);
if (str != NULL) {
printf("%s\n", str);
free(str); // Never forget freeing the pointer to avoid the memory leak
}
return 0;
}
char *strcaT(char *t, char *s) {
char *a = malloc(strlen(t) + strlen(s) + 1);
if (!a) {
return NULL;
}
int i;
for(i = 0; t[i] != '\0'; i++) {
a[i] = t[i];
}
for(int j = 0; s[j] != '\0'; j++,i++) {
a[i] = s[j];
}
a[i] = '\0';
return a;
}
For starters the function strcaT should append the string specified by the second parameter to the end of the string specified by the first parameter. So the first parameter should point to a character array large enough to store the appended string.
Your function is incorrect because at least it returns a (invalid) pointer to a local variable length character array that will not be alive after exiting the function and moreover the array has a less size than it is required to store two strings that is instead of
char buffer[strlen(t) + strlen(s) - 1];
^^^
it should be declared at least like
char buffer[strlen(t) + strlen(s) + 1];
^^^
and could be declared as static
static char buffer[strlen(t) + strlen(s) + 1];
Also the nested loops do not make sense.
Pay attention that you should provide the function prototype before calling the function. In this case the compiler will be able to check passed arguments to the function. And the name of the function strcaT is confusing. At least the function can be named like strCat.
The function can be defined the following way
#include <stdio.h>
#include <string.h>
char * strCat( char *s1, const char *s2 )
{
char *p = s1 + strlen( s1 );
while ( ( *p++ = *s2++ ) );
return s1;
}
int main(void)
{
enum { N = 14 };
char s1[N] = "first";
char *s2 = "second";
puts( strCat( s1, s2 ) );
return 0;
}
The program output is
firstsecond
On the other hand if you are already using the standard C function strlen then why not to use another standard C function strcpy?
With this function your function could be defined more simpler like
char * strCat( char *s1, const char *s2 )
{
strcpy( s1 + strlen( s1 ), s2 );
return s1;
}
If you want to build a new character array that contains two strings one appended to another then the function can look for example the following way.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * strCat( const char *s1, const char *s2 )
{
size_t n1 = strlen( s1 );
char *result = malloc( n1 + strlen( s2 ) + 1 );
if ( result != NULL )
{
strcpy( result, s1 );
strcpy( result + n1, s2 );
}
return result;
}
int main(void)
{
char *s1 = "first";
char *s2 = "second";
char *result = strCat( s1, s2 );
if ( result ) puts( result );
free( result );
return 0;
}
Again the program output is
firstsecond
Of course calls of the standard C function strcpy you can substitute for your own loops but this does not make great sense.
If you are not allowed to use standard C string functions then the function above can be implemented the following way.
#include <stdio.h>
#include <stdlib.h>
char * strCat( const char *s1, const char *s2 )
{
size_t n = 0;
while ( s1[n] != '\0' ) ++n;
for ( size_t i = 0; s2[i] != '\0'; )
{
n += ++i;
}
char *result = malloc( n + 1 );
if ( result != NULL )
{
char *p = result;
while ( ( *p = *s1++ ) != '\0' ) ++p;
while ( ( *p = *s2++ ) != '\0' ) ++p;
}
return result;
}
int main(void)
{
char *s1 = "first";
char *s2 = "second";
char *result = strCat( s1, s2 );
if ( result ) puts( result );
free( result );
return 0;
}
I have changed your program to look like below:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char* strcaT();
char* a = "first";
char* b = "second";
printf("%s",strcaT(a,b));
return 0;
}
char* strcaT(char *t, char *s)
{
char* a = (char*)malloc(sizeof(char)*(strlen(t) + strlen(s) + 1));
for(int i=0; i<strlen(t); i++) {
a[i] = t[i];
}
for(int i=0; i<strlen(s); i++) {
a[strlen(t) + i] = s[i];
}
a[strlen(t)+strlen(s)] = '\0';
return a;
}
You are getting segfault because you are returning address of a local array which is on stack and will be inaccessible after you return. Second is that your logic is complicated to concatenate the strings.
This is my task:
Realize function that reverses null terminated string. The prototype of the function is void Reverse(char *ptr);. Do not use standard library functions.
This is my code for now:
void Reverse(char *ptr) {
char *newString;
char ch = *ptr;
unsigned int size = 0;
for (int i = 1; ch != '\0'; i++) {
ch = *(ptr + i);
size++;
}
newString = (char*)malloc(size);
for (int left = 0, right = size - 1; left < size; left++, right--) {
*(newString + left) = *(ptr + right);
}
printf("%s", newString);
printf("\n");
}
It reverses the string and saves it in the newString
My first problem is that when I print the newString to see if the functions works the string is reversed, but after it there are some symbols.
For example:
If I have char *str = "hello"; and Reverse(str); in the main method
the result of printf("%s", newString) will be olleh****.
But if change the
newString = (char*)malloc(size); to
newString = (char*)malloc(1); it works fine.
My second problem is that I don't know how to save the newString into the given one. I am using a new String because the given one can't be changed.
For starters it is better to declare the function like
char * Reverse( char *ptr );
^^^^^^
because standard C string functions usually return pointers to destination strings.
The function should reverse the original string. It may not create a dynamic string because the caller of the function will be unable to free it provided that the function has return type void.
The function can look as it is shown in the following demonstrative program.
#include <stdio.h>
char * Reverse( char *ptr )
{
char *first = ptr, *last = ptr;
while ( *last ) ++last;
if ( first < last )
{
for ( ; first < --last; ++first )
{
char c = *first;
*first = *last;
*last = c;
}
}
return ptr;
}
int main( void )
{
char s[] = "Hello World!";
puts( s );
puts( Reverse( s ) );
return 0;
}
Its output is
Hello World!
!dlroW olleH
Take into account that you may not call the function like
puts( Reverse( "Hello World!" ) );
because string literals are immutable in C.
If you are going to declare the function like
void Reverse( char *ptr );
then just remove the return statement in the shown function. For example
#include <stdio.h>
void Reverse( char *ptr )
{
char *first = ptr, *last = ptr;
while ( *last ) ++last;
if ( first < last )
{
for ( ; first < --last; ++first )
{
char c = *first;
*first = *last;
*last = c;
}
}
}
int main( void )
{
char s[] = "Hello World!";
puts( s );
Reverse( s )
puts( s );
return 0;
}
If to use your approach with indices then the function can look like
#include <stdio.h>
void Reverse( char *ptr )
{
size_t size = 0;
while ( *( ptr + size ) ) ++size;
if ( size != 0 )
{
for ( size_t left = 0, right = size - 1; left < right; left++, right-- )
{
char c = ptr[left]; // or char c = *( ptr + left ); and so on
ptr[left] = ptr[right];
ptr[right] = c;
}
}
}
int main( void )
{
char s[] = "Hello World!";
puts( s );
Reverse( s );
puts( s );
return 0;
}
In your loop to get the size, you're not counting the null terminator. So your newString is missing the null terminator as well. make sure to do newString = malloc(size + 1);, and to place the null terminator onto the end of newString.
You have several problems in your code:
you do not allocate enough space for the resulting string, you must allocate size+1 bytes and set the \0 terminator at the end of the string.
you only copy half the characters from ptr to newString.
you are not even supposed to allocate memory, since you cannot call any library functions. You should instead reverse the string in place.
Your test fails because modifying a string literal invokes undefined behavior. You should pass an initialized array as shown below.
Here is an improved version:
#include <stdio.h>
void Reverse(char *ptr) {
unsigned int left, right;
for (right = 0; *(ptr + right) != '\0'; right++) {
continue;
}
for (left = 0; left < right; left++, right--) {
char ch = ptr[left];
ptr[left] = ptr[right - 1];
ptr[right - 1] = ch;
}
}
int main(void) {
char buf[] = "Hello world";
Reverse(buf);
printf("%s\n", buf);
return 0;
}
It should print dlrow olleH.
Simple string reverse function without string.h library functions :
#include <stdio.h>
void reverse(char *str, int n);
int main()
{
char str[100];
int n;
printf("Enter a string\n");
scanf("%s",&str);
for( n = 0; str[n] != '\0'; n++)
{
}
reverse(str,n);
puts(str);
return 0;
}
void reverse(char *str,int n)
{
printf("Length = %d\n",n);
printf("Reversed :\n");
int i;
char ch;
for(i = 0; i<n/2; i++)
{
ch = str[i];
str[i] = str[n-i-1];
str[n-i-1] = ch;
}
}