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);
}
Related
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 am rather new to the C language right now and I am trying some practice on my own to help me understand how C works. The only other language I know proficiently is Java. Here is my code below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char * reverse(char word[]);
const char * reverse(char word[]) {
char reverse[sizeof(word)];
int i, j;
for (i = sizeof(word - 1); i <= 0; i--) {
for (j = 0; j > sizeof(word - 1); j++) {
reverse[i] = word[j];
}
}
return reverse;
}
int main() {
char word[100];
printf("Enter a word: ");
scanf("%s", word);
printf("%s backwards is %s\n", word, reverse(word));
return 0;
}
When the user enters a word, the program successfully prints it out when i store it but when i call the reverse function I made it doesnt return anything. It says on my editor the address of the memory stack is being returned instead and not the string of the array I am trying to create the reverse of in my function. Can anyone offer an explanation please :(
sizeof(word) is incorrect. When the word array is passed to a function, it is passed as a pointer to the first char, so you are taking the size of the pointer (presumably 4 or 8, on 32- or 64-bit machines). Confirm by printing out the size. You need to use strlen to get the length of a string.
There are other problems with the code. For instance, you shouldn't need a nested loop to reverse a string. And sizeof(word-1) is even worse than sizeof(word). And a loop that does i-- but compares i<=0 is doomed: i will just keep getting more negative.
There are multiple problems with your reverse function. C is very different from Java. It is a lot simpler and has less features.
Sizes of arrays and strings don't propagate through parameters like you think. Your sizeof will return wrong values.
reverse is an identifier that is used twice (as function name and local variable).
You cannot return variables that are allocated on stack, because this part of stack might be destroyed after the function call returns.
You don't need two nested loops to reverse a string and the logic is also wrong.
What you probably look for is the function strlen that is available in header string.h. It will tell you the length of a string. If you want to solve it your way, you will need to know how to allocate memory for a string (and how to free it).
If you want a function that reverses strings, you can operate directly on the parameter word. It is already allocated outside the reverse function, so it will not vanish.
If you just want to output the string backwards without really reversing it, you can also output char after char from the end of the string to start by iterating from strlen(word) - 1 to 0.
Edit: Changed my reverse() function to avoid pointer arithmetic and to allow reuse of word.
Don't return const values from a function; the return value cannot be assigned to, so const doesn't make sense. Caveat: due to differences between the C and C++ type system, you should return strings as const char * if you want the code to also compile as C++.
Arrays passed as params always "decay" to a pointer.
You can't return a function-local variable, unless you allocate it on the heap using malloc(). So we need to create it in main() and pass it as a param.
Since the args are pointers, with no size info, we need to tell the function the size of the array/string: sizeof won't work.
To be a valid C string, a pointer to or array of char must end with the string termination character \0.
Must put maximum length in scanf format specifier (%99s instead of plain %s — leave one space for the string termination character \0), otherwise vulnerable to buffer overflow.
#include <stdio.h> // size_t, scanf(), printf()
#include <string.h> // strlen()
// 1. // 2. // 3. // 4.
char *reverse(char *word, char *reversed_word, size_t size);
char *reverse(char *word, char *reversed_word, size_t size)
{
size_t index = 0;
reversed_word[size] = '\0'; // 5.
while (size-- > index) {
const char temp = word[index];
reversed_word[index++] = word[size];
reversed_word[size] = temp;
}
return reversed_word;
}
int main() {
char word[100];
size_t size = 0;
printf("Enter a word: ");
scanf("%99s", word); // 6.
size = strlen(word);
printf("%s backwards is %s\n", word, reverse(word, word, size));
return 0;
}
#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);
}
}
I have to compare few characters of string say from 2nd char till 4th character( counting starts from zero)
The string is stored in elements of structure say zoopla->real
for example zoopla ->real has '447889036' where real is of type char real[20];
Also please note I cant use function strnstr.
The code works as expected but just for curiousity, I have added printf statement and it shows me value till 4th cahr and then some garabe characters.
I want to know why the printf statment is showing 2 extra garabe values?
char * copyTemp;
char *strptr;
copyTemp = (char *)malloc(sizeof(char)*6);
strncpy(copyTemp, zoopla->real, 5);
printf("the string copied is %s", copyTemp); // debug statemnt
strptr = strstr(copyTemp, "666");
if(strptr != NULL)
{
//some other function
}
else
//some other function
free(copyTemp);
All criticism and suggestions are welcome
It seems to me that copyTemp is not null terminated. That's why printf shows you garbage characters after the characters you put in there. It doesn't know where to stop so it continues iterate through memory.
Add
copyTemp[5] = '\0';
after strncpy.
See this example from the documentation of strncpy:
/* strncpy example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[]= "To be or not to be";
char str2[6];
strncpy (str2,str1,5);
str2[5]='\0';
puts (str2);
return 0;
}
see
http://www.cplusplus.com/reference/clibrary/cstring/strncpy/
No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.
you have to add null your self.
if you will be allocating memory of constant size then use array only.
#include <stdio.h>
#include <string.h>
int main ()
{
char * copyTemp;
char *strptr;
copyTemp = (char *)calloc(sizeof(char),6);
strncpy(copyTemp, "88666782921", 5);
printf("the string copied is %s", copyTemp); // debug statemnt
strptr = strstr(copyTemp, "666");
if(strptr != NULL)
{
//some other function
}
else
//some other function
free(copyTemp);
return 0;
}
According to my old K&R, strncpy will only implicitly add null bytes if the source string has fewer characters than the number to be copied.
In this case, zoopla->real has more than 5 characters, so the function is simply copying the first five characters. Since you haven't initialized the memory to zero, or explicitly added a null byte, the string is not terminated after the fifth character. So when you print the string, you get additional bytes with essentially random values, until one is hit that happens to be zero.
An array of pointers to strings is provided as the input. The task is to reverse each string stored in the input array of pointers. I've made a function called reverseString() which reverses the string passed to it. This functions works correctly as far as i know.
The strings stored/referenced in the input array of pointers are sent one by one to the reverseString() function. But the code hangs at some point in the reverseString() function when the values of the passed string are swapped using a temp variable. I can't figure out why the code is hanging while swapping values. Please help me with this.
The code is as follows:
#include <stdio.h>
void reverseString(char*);
int main()
{ char *s[] = {"abcde", "12345", "65gb"};
int i=0;
for(i=0; i< (sizeof(s)/sizeof(s[0]) ); i++ )
{ reverseString(s[i]);
printf("\n%s\n", s[i]);
}
getch();
return 0;
}//end main
void reverseString(char *x)
{ int len = strlen(x)-1;
int i=0;
char temp;
while(i <= len-i)
{ temp = x[i];
x[i] = x[len-i];
x[len-i] = temp;
i++;
}
}//end reverseString
You are trying to change string literals.
String literals are usually not modifiable, and really should be declared as const.
const char *s[] = {"abcde", "12345", "65gb"};
/* pointers to string literals */
If you want to make an array of modifiable strings, try this:
char s[][24] = {"abcde", "12345", "65gb"};
/* non-readonly array initialized from string literals */
The compiler will automatically determine you need 3 strings, but it can't determine how long each needs to be. I've made them 24 bytes long.
The strings ("abcde" etc) could be stored in readonly memory. Anything is possible when you try to modify those strings, therefore. The pointers to the strings are modifiable; it is just the strings themselves that are not.
You should include <string.h> to obtain the declaration of strlen(3), and another header to obtain the function getch() - it is not in <stdio.h> on my MacOS X system (so I deleted the call; it is probably declared in either <stdio.h> or <conio.h> on Windows).
Hope this helps you! what i am doing here is that i am going to the address of the last character in the string then printing them all by decreasing the pointer by 1 unit (for character its 2 bytes(please check)).
//program to reverse the strings in an array of pointers
#include<stdio.h>
#include<string.h>
int main()
{
char *str[] = {
"to err is human....",
"But to really mess things up...",
"One needs to know C!!"
};
int i=0; //for different strings
char *p; //declaring a pointer whose value i will be setting to the last character in
//the respective string
while(i<3)
{
p=str[i]+strlen(str[i])-1;
while(*p!='\0')
{
printf("%c",*p);
p--;
}
printf("\n");
i++;
}
}