#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void rec(char pin[]);
main()
{
char pin[100];
printf("Give word: ");
scanf("%s", pin);
rec(pin);
system("pause");
}
void rec(char pin[])
{
int i=0;
if (pin[i]=='\0')
return;
else
{
rec(pin[i+1]);
printf("%c", pin[i]);
}
}
Well seems not to work but I don't know why.
(I am not allowed to use the for loop, the function strlen and things like that).
in rec function else part you are passing a element which should be address of element.so try this in else part
else
{
rec(&pin[i+1]);
printf("%c", pin[i]);
}
Well, since your question is "why it doesn't work", might as well answer exactly that.
I'm going to assume that the re() declaration is just a typo for rec() -- of course you have to correct that.
In the first line of that function, you declare a variable, int i = 0;. However, that variable is never assigned to again. Scan the function for any assignment on i -- you won't find any. Therefore, that i variable is a constant 0. With that in mind, let's replace i by 0 and write the code again:
if (pin[0]=='\0')
return;
else
{
rec(pin[1]);
printf("%c", pin[0]);
}
The offending line is clearly rec(pin[1]). The function expects a char * argument, i.e., a string (note that char * and char [] are the same in function parameter declarations). However, pin[1] is just the second character of pin. What you're doing there is converting implicitly that character to a pointer and passing it to the function -- which is incorrect.
What you want to pass to rec() is the pointer to the second character, since that would make it a pointer to a string beginning at the second character of pin. So, the correct call would be rec(pin + 1), not rec(pin[1]). Since pin points to the first character of the string, pin + 1 points to the second.
This is not correct. First of all, you are using an automatic variable. so, 'i' will always be initialized to 0.
use static int i, and see carefully. you are throwing char to char*. so, you cannot throw rec(pin[i+1]); change this to rec(pin); and before printf("%c", pin[i]); decrement 'i', before calling rec recursively, increment 'i' . Last but not least, you are calling 'rec'. but function name is 're', where is c???
void rec(char pin[]){
if (*pin=='\0')
return;
else {
rec(pin + 1);
printf("%c", *pin);
}
}
Related
I'm new to C and am trying to write a simple function that can take in a string (or array of characters) and convert its case based on the following rules:
The first character should be uppercase.
The remaining characters should be lowercase.
I've written code, but I'm running into segmentation fault errors, and I'm baffled as to what's going wrong. Here's what I've written:
void myFunction(char name[]) {
printf("Before: %s", name);
name[0] = toupper(name[0]); // This line seems to cause problems.
// Convert the other letters to lowercase if they aren't already.
for(int i = 1; name[i] != '\0'; i++) {
if(islower(name[i])) {
name[i] = tolower(name[i]);
} else {
name[i] = name[i];
}
}
name[i] = '\0';
printf("After: %s", name);
}
void my_caller(*name1) {
printf("Name before changing case: %s\n", name1);
myFunction(name1);
printf("Name after changing case: %s\n", name1);
}
// In another .c file.
int main() {
char name1[] = "adam";
my_caller(&name1);
}
In myFunction, if I comment out the lines except for
name[0] = toupper(name[0]);
I still get the segmentation fault. So that would suggest that this line is (one of) the culprits, but I don't understand why. I want to convert the letter to uppercase and put it back into the string.
To start with, having a function definition like
void my_caller(name1)
is problematic, as missing type (used to be, now obsolete rule) default to int. You want this to be a char *. not int.
You need to change it to
void my_caller(char * name1) {....
Moreover, you need to call the function as my_caller(name1);, passing an array is the same as passing a pointer to the first element of the array.
Also, you don't pass the address of the array (check the types if you're in confusion) while calling the function.
That said, inside myFunction(), the scope of i is limited to the for loop only, but you want to use that beyond the scope (to null-terminate), so you got to declare i in the function block scope.
Moral of the story: Turn up the compiler warning / error settings, and pay close attention to the messages emitted by the compiler. They are there for a reason.
Note: After making these changes, code works as expected.
Here's my code and I can't seem to figure out how to make the function with only the array as argument.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char strArray[30] = "Print this string backward.";
puts("");
stringReverse(strArray);
return(0);
}
void stringReverse(char strArray[])
{
if(strArray != "\n") {
stringReverse(&strArray)
printf("%s", strArray)
}
}
A few observations and criticisms:
The math.h and stdlib.h header files are not needed for the posted code. While char strArray[30] is large enough to hold the input string, it is better to use empty brackets in a string initializer unless you need a specific size that is larger than the initial string. This is less error-prone, and just easier, since there is no need to count characters, and no need to remember to include space for the null-terminator. You probably want to move the puts(""); to after the call to stringReverse(), since this function does not print a newline character. It usually seems better to use putchar('\n'); for something like this; putchar() is designed to print only one character, and so is the right tool for the job.
It seems that with the statement if (strArray != "\n") {} the goal is to check if the first character is a newline, but there are a few problems with this. First, "\n" is a string, not a character; next, strArray is a pointer to the first character of the array strArray[], not the first character itself. There is no '\n' character in the input string, so even if this condition were correctly written, it would always be true, and this code would enter an infinite recursion. Finally, the argument passed to stringReverse() is never changed, so there is no way for the recursion to end. For recursion to succeed, a base case must be converged upon.
A solution is to compare the first character of the array with '\0'. If the first character is not the null-terminator, the stringReverse() function is called again, this time with the value strArray + 1. The program will continue recursively calling stringReverse() until an empty string is passed in, at which point the final call to stringReverse() returns to its caller (the previous call to stringReverse()), where the last character of the string is printed, before returning to its caller,.... Each of the stringReverse() frames is returned to, in the reversed order in which they were called, and each of these frames prints a character of the string, until finally the first frame is reached, and the first character is printed, before returning to main().
Note that in a function call, and in fact most expressions, arrays decay to pointers to their first elements. So, in stringReverse() strArray is a pointer to char that points to the first element of the array provided as an argument by the caller. Also note that in a function declaration such as void stringReverse(char strArray[]) array types are adjusted to appropriate pointer types, so this declaration is equivalent to void stringReverse(char *strArray).
#include <stdio.h>
void stringReverse(char strArray[]);
int main(void)
{
char strArray[] = "Print this string backwards.";
stringReverse(strArray);
putchar('\n');
return 0;
}
void stringReverse(char strArray[])
{
if (*strArray != '\0') {
stringReverse(strArray + 1);
putchar(*strArray);
}
}
Program output:
.sdrawkcab gnirts siht tnirP
First, you need to return an value.
Then, what your algorithm should to do? Run until the final of your string and then return variable by variable in reverse with just one parameter, well you just need pass this parameter shorter every loop.
Like this:
#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
void stringReverse(char strArray[], int i) {
if (strArray[0] != NULL)
if (strArray[0] != '\0') {
int c = 0;
char str[30];
while (c < strlen(strArray)) {
str[c] = strArray[2 + c -1];
c++;
}
str[c] = '\0';
stringReverse(str);
}
printf("%c", strArray[0]);
}
int main(int argc, char *argv[]) {
char strArray[30] = "Print this string backward.";
stringReverse(strArray, 0);
printf("\n\n");
system("Pause");
return(0);
}
I am just starting to work with functions and wish to read an entire array of user input and convert all entries to uppercase. I am still a little confused how to change things in functions and have the changes occur in the array in the main program.
The code I attached is not working:
Any help and/or explanation would be appreciated.
Thank you
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
// function to turn all user input to uppercase
turnUpCase(char *in,200)
{
char *p;
for (p=in; *p='\0'; ++p)
{
*p = toupper(*p);
}
}
int main(void)
{
char input[200];
int i = 0;
printf("Welcome to the Morse translator.\n");
printf("Enter input: ");
fgets(input, sizeof(input), stdin);
// call to function to turn all input into uppercase
turnUpCase(&input);
return 0;
}
For your turnUpCase function:
1- You are not mentioning any return type.
2- what is 200 ?? write it as retyrn_type turnUpCase(char *p, int size)
in for loop write it as
for (p=in; *p!='\0'; ++p) //to compare with anything use '=='
Name of array is always a pointer. You don't need to mention like turnUpCase(&input). let it go like turnUpCase(input,200)
modify:
turnUpCase(&input); //turnUpCase(input)
turnUpCase(char *in,200) //turnUpCase(char *in)
*p='\0' // *p!='\0'
To make your code work, first you need to change the declaration for turnUpCase() to something like:
void turnUpCase(char *in){}
Since your function does not return a value, it should be declared to be of type void. Next, in the for-loop of the function itself, you have an assignment instead of a comparison. Try this:
for (p = in; *p != '\0'; ++p){}
Finally, when you pass an array to a c function, you are really passing a pointer to the first element of the array, so in your case turnUpCase(input) passes a pointer to the first character of the input string to your function. The way you wrote it, you are passing the address of a pointer to the first character.
Incidentally, I might have written your function like this:
void to_upper(char *str)
{
while(*str) {
*str = toupper(*str);
++str;
}
}
change turnUpCase(&input); to turnUpCase(input); ( an array if passed to a function, "decays" to a pointer to its 1st element, so you don't need to use &) and
also:turnUpCase(char *in,200) to void turnUpCase(char *in) and *p='\0' to *p!='\0'.`
I didn't check if there are the proper libraries for this code to run, but the corrected code seems to be:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
First, we need to declare the method. C needs it inside the header or before the function. Be aware of that this declaration has no body, and ends with ;. After that, we can define the function.
// function to turn all user input to uppercase
void turnUpCase(char *in);
every function needs a return type defined before the definition. Here's the definition and body of the function:
void turnUpCase(char *in) {
char *p;
for (p=in; *p; p++) *p = toupper(*p);
}
Note: As #DavidBowling suggested, this code can be rewritten as (I prefer keeping the original pointer as it was) :
void turnUpCase(char *in) {
char *p = in;
while(*p){
*p = toupper(*p);
p++;
}
}
Both methods check the chars until it reaches a zero char/string end char/null char. Every string in C ends with an \0 (0x00) character, so the function tells that until our string ends, loop the chars and make every char uppercase.
Now the magic begins:
int main(void) {
char input[200];
int i = 0;
printf("Welcome to the Morse translator.\n");
printf("Enter input: ");
fgets(input, sizeof(input), stdin);
Here, you don't need the addressing & operator, because in C, char arrays are already a pointer to it's contents. But, you might give the first char's address to the method too. So there are two options.
First:
// call to function to turn all input into uppercase
turnUpCase(input);
Second:
// call to function to turn all input into uppercase
turnUpCase(&input[0]);
Then, you can print the result to user.
printf("The uppercase version is: %s", input);
return 0;
}
i compile your code with c++ 4.2.1, and it seems has some compilation error.
when you claim a string, input variable is the pointer of first char in string, so it should be turnUpCase(input) when you call the function.
if want to change variable in function, you need to pass pointer or reference into it. in this case, pass input is just fine.
the reason your code not work may be:
for (p=in; *p='\0'; ++p)
should be:
for (p=in; *p=='\0'; ++p)
I wrote a function that cuts all the left space of an inputted string. These two functions give the same output "haha" when input is " haha".
My question are:
1) Why the 1st one need return but the 2nd one doesn't. I added "return s" and it made a syntax error.
2) Are there any different in these if I use it in another situation?
3) Many said that 2nd one return a character not a string, how about my output ?
char *LTrim(char s[])
{
int i=0;
while(s[i]==' ')i++;
if (i>0) strcpy(&s[0],&s[i]);
return s;
}
and
char LTrim(char s[])
{
int i=0;
while(s[i]==' ')i++;
if (i>0) strcpy(&s[0],&s[i]);
}
This is my main():
int main()
{
char s[100];
printf("input string ");
gets(s);
LTrim(s);
puts(s);
return 0;
}
Your second code segment doesn't seem to have a return statement, please correct that for getting the correct answer.
The first function is returning a character pointer, which will be memory pointing to the starting location of your character array s, whereas the second function is returning a single character.
What you do with the values returned is what will make the difference, both the codes seem to be performing the same operation on the character array(string) passed to them, so if you are only looking at the initial and final string, it will be same.
On the other hand, if you actually use the returned value for some purpose, then you will get a different result for both functions.
char *LTrim(char s[]){} is a function of character array / string which returns character pointer i.e. returns reference / memory address.
While char LTrim(char s[]) is a function of character array / string, which return character only.
char is a single character.
char * is a pointer to a char.
char * are mostly used to point to the first character of a string (like sin your example).
In the first example you return your modified svariable, and in the second you return nothing so it's best to change the return value to void instead of char.
I have a doubt in my program
#include<stdio.h>
int myFunc(char **);
main()
{
char *a[2]={"Do","While"};
myFunc(a);
}
int myFunc(char **P)
{
/* Here I want to print the strings passed but I'm unable to
print the strings I just tried the below statement which
printed just the first letter which is 'D'*/
printf("%c",**P);
}
when i tried
printf("%s",**P);
I am getting run time error. so can anyone please help me out?
Thanks
Madhu
Put size as parameter to allow the function to know how many strings you have in your array. Then, you should iterate the array and print each one.
int myFunc( char** p, int size)
{
for( int i = 0; i < size; ++i)
{
printf("%s", p[i]);
}
}
Later edit (as requested :-) )
int main( int, char**)
{
char *a[2]={"Do","While"};
myFunc( a, 2); // Could be myFunc( a, sizeof(a)/sizeof(char*));
// ...
return 0;
}
Too many stars - try
printf("%s",*P);
And you need %s format specifier - %c is just for single character.
If you want to print all strings, you need to pass number of strings in array and then print these strings from the loop.
Check the code suggested by Cătălin Pitiș. To pass the number of strings, you call function like this:
myFunc(a, sizeof(a)/sizeof(a[0]));
for( int i = 0; i < 2; i++ ) {
char* string = P[i];
printf( "%s", string );
}
And you shoud use some way of passing size of array into the function - either pass it as an int parameter,
int myFunc(char **P, int size)
{
for( int i = 0; i < size; i++ ) {
//whatever here
}
}
or always append a zero value to the array and only loop until you find that zero value.
char* array[] = { "String1", "String2", 0 };
Otherwise you will have hard to maintain code.
I like objective-c style nil (0) terminated arrays:
void myFunc(char **P)
{
while (*P) // loop to iterate over all strings until 0
printf("%s\n",*P++); // print and move to next element in array
}
int main()
{
char *a[]={"Do","While",0}; // added 0 to null terminate array,
myFunc(a); // kind of like string
}
Output:
Do
While
First, the good news: the type of a is equivalent to char **, so you are passing a valid parameter to myFunc().
The first problem is that %c is a format specifier that means print a single character. Since **P is an expression that evaluates to a single character, your first version does exactly what you told it to do. That isn't what you want.
The second version is close to syntactically correct. It should read printf("%s", *P), where *P is an expression that evaluates to a pointer to a nul-terminated ASCII string. In this case, it evaluates to "Do". This version won't print both strings.
Although it is true that the name of an array is the same as a pointer to its first element, that is a kind of "lie to students". Passing an array to a function does not and cannot convey the length of the array. To do that, you need either a second argument containing the length, or a convention like the nul-terminator on a string to indicate the end of the array. With that change, you can modify myFunc() to use a loop over the elements passed and print each one.
The problem in your code is that you want to print a string (char*) but you're giving it a char. Remember that P is an array of char*. When you de-reference it once, you get a char*; when you do it a second time, you just get the char at the beginning of the char*.
When you try to use the char value with the %s specifier, it treats the value as a pointer, and tries to dereference that value. Hence, it will try to print the "string" at the memory location X, where X is the value of the char (i.e. a value from 0 to 255). This gives you an access violation/segmentation fault (the error you see at runtime).
The best workarounds for this, as noted by Cătălin Pitiș and RBerteig, are to either:
pass another parameter to specify the length of the array
add an additional null at the end of the array.
if you don't want to keep and pass around array size::
int myFunc(char **);
main()
{
char *a[2]={"Do","While", NULL};
myFunc(a);
}
int myFunc(char **P)
{
if( !P )
return 0;
while(*P != NULL)
{
printf("%s",*P);
P++;
}
}
Wrong Answer: I think you may have to dereference P when you print it, although I could be wrong.
EDIT: I'm tired, it's 3 am here but I don't feel like sleeping so I'm here trying to answer questions. After reading the criticism, I reread the question and noticed that he does dereference P, but as is stated in another answer, it's dereferenced too much. When one wants to print a char string, one wants to pass a pointer as the char string is really an array.
Another EDIT: I would also like to point out that the person who asked the question made an edit after I answered and that when I first answered it didn't read "printf("%s",**P);" it read "printf("%s", P);" and the last part was bold.