How can I convert char[] array to char* [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I want to convert my char[] array to char* string in C programing language. Here is what I did. But I can't reach the solution . Please help me. Here is my code:
#include <stdio.h>
void fnk(char *chr){
printf("%s",chr);
}
int main(){
char charfoo[100];
int i=50;
gets(charfoo);
for(int j=0;j<i;j++){
fnk((char*) charfoo[j]);
}
}

I think you mean the following
fnk( &charfoo[i]);
Take into account that it would be better to write the loop the following way
for( int j=0; charfoo[j]; j++ ) {
fnk( &charfoo[j]);
}
Also function gets is unsafe and is not supported any more by the C Standard. Instead use function fgets For example
fgets( charfoo, sizeof( charfoo ), stdin );
In this case the loop can look like
for( int j=0; charfoo[j] != '\0' && charfoo[j] != '\n'; j++ ) {
fnk( &charfoo[j]);
}
If you want to output just one character in the function then the function should be defined like
void fnk(char chr){
printf("%c",chr);
}
and called like
fnk( charfoo[j]);

If we switch from gets() to fgets() as Vlad from Moscow suggests, then the return value from fgets() is of the same type as the argument to fnk() so we can just pass the result along:
#include <stdio.h>
void fnk(char *string) {
printf("%s", string);
}
int main() {
char charfoo[100];
fnk(fgets(charfoo, sizeof(charfoo), stdin));
return 0;
}
The next step in sophistication would be to save the result of fgets() to a char * pointer and test if it's NULL or not before passing it along (or not) to fnk().
If you want an actual char * copy of the array charfoo[] to exist in memory and not simply pass off char[] arrays as char * pointers, you could do the following which throws in lots of error checking too:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fnk(char *string) {
printf("%s", string);
}
int main() {
char charfoo[100];
char *input = fgets(charfoo, sizeof(charfoo), stdin);
if (input != NULL) {
char *string = strdup(input);
if (string != NULL) {
fnk(string);
free(string);
}
}
return 0;
}
But in all cases, it seems like you're making things more difficult than they need to be.

Calling fnk with i would just be the same call 50 time -- assuming you want to use j instead the code would look like this
#include <stdio.h>
void fnk(char *chr){
printf("%s",chr);
}
int main(){
char charfoo[100];
int i=50;
gets(charfoo);
for(int j=0;j<i;j++){
fnk(charfoo + j);
}
}
be aware that gets could cause buffer overflow if the input is longer than the charfoo (i.e. 99 bytes + newline + null) -- but that is a different story

Related

Why the code below excutes unexpected letters in the end of the string?

This is my code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int countNumber(char string[],int number_[]);
int countNumber(char string[]);
int main(){
char string[] = "tran_huynh_minh_phuc";
int num = countNumber(string)+1;
int *number = (int *) calloc(num, sizeof(int));
countNumber(string,number);
for(int i=0;i<num;i++){
printf("%d\n",number[i]);
}
fflush(stdin);
char a[3][14];
strncpy(a[2], string+5, 5);
printf("%s",a[2]);
}
int countNumber(char string[],int *number)
{ int count=0;
int num_i=1;
number[0]=-1;
for(int i=0; i<strlen(string); i++)
{
if(string[i]=='_')
{ number[num_i] = i;
num_i++;
}
}
return count;
}
int countNumber(char string[])
{ int count=0;
for(int i=0; i<strlen(string); i++)
{
if(string[i]=='_')
{
count++;
}
}
return count;
}
this is my problem console results:
I am doing the program to get the substring which will get "tran","huynh","minh" from "tran_huynh_minh", however it is appearing some unexpected letters at the end of my substring. In addition, I tried many ways to fix it but it did not work. Can you find my mistakes?
Thanks
Minh Phuc
I think the intent for the bottom of the main block is something like this (this adds the null after the 'huynh' which was copied. By adding the null, when it goes to print a2, it knows when to stop. It looks like the desire was to put the second word in the array at index 2 (presumably being done in a loop once it was working or the like):
strncpy(a[2], string + 5, 5);
a[2][5] = '\0';
printf("%s", a[2]);
If you run something equivalent to this, you should see the expected output. However, you likely also see a warning on the strncpy function and considering using strncpy_s (depending what you are using to compile. It looks like you are on windows). If you replace the function call with strncpy_s (assuming Visual Studio), you will get the desired result without adding the null at the end separately. Note it expects a size of the destination array as a safeguard (14 in this case).
See this link as well as this one.

Error with the array returning through function

I need to read a word from main function and convert the characters in UCASE if the first character is LCASE and vice versa using the user defined function.I tried ways for returning the array from function but still I am lacking some core ideas. Please debug this program and explain the way it works.
#include <stdio.h>
#include <string.h>
int* low (char str)
{
int i;
for (i=1; i<strlen(str);i++)
{
if(str[i]<91)
{
str[i]=str[i]+32;
}
else
{
}
}
return &str;
}
int* high (char str[50])
{
int i;
for (i=0; i<strlen(str);i++)
{
if(str[i]>91)
{
str[i]=str[i]-32;
}
else
{
}
}
return &str;
}
void main()
{
char str[50];
char* strl;
printf("Enter any string....\n");
scanf("%s",str);
if (str[0]<91)
{
*strl=low(str);
}
else
{
*strl=high(str);
}
printf("Converted string is %s.",*strl);
}
There is already a problem here:
So if you are saying this code is perfect and you want us to debug it and explain how (on earth) this works, then here you go.
In function int* low (char str), you have if(str[i]<91). Thats a problem right there. str is a char received as an argument, and hence str[i] is a straight compile-time error.
Another one to deal with is the return statement.
You have a statement:
return &str;
which would return the address of str, which by the way is a char, whereas function low is supposed to return a pointer to an int.
The same is applicable to high function as well.
Suggestion: Leave aside this bad code and get a beginner level C programming book first. Read it and the try some codes out of it.
A few inputs for improvement: (Which you may not comprehend)
change
void main()
to
int main(void)
Why? Refer this legendary post: What should main() return in C and C++?
Secondly, int both functions you are using strlen() in loop which will always return a fixed value. So, instead of
for (i=0; i<strlen(str);i++)
I'd suggest,
size_t strlength = strlen(str);
for (i=0; i < strlength; i++)
You can try the code and method as below:
#include <stdio.h>
#include <string.h>
char* caseConverter (char *str)
{
int i;
for (i=0; i<strlen(str);i++)
{
if(str[i]>=65 && str[i]<=90)
{
str[i]=str[i]+32; //To lower case
}
else if((str[i]>=97 && str[i]<=122))
{
str[i]=str[i]-32; //To upper case
}
else
printf("%c is not an alphabet \n",str[i]);
}
return str;
}
void main()
{
char inputStr[50]= "Stubborn";
char* opStr= caseConverter(inputStr);
printf("Converted string is %s",opStr);
}

How to toupper char array in c? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
whats wrong here?
I want to check if the char in char array islower, so if it is it should be changed in uppercase.
#include <stdio.h>
int main(int argc, char *argv[]) {
char arr[100];
scanf("%s",&arr);
for(int i=0;i<sizeof(arr);i++){
if(int islower(arr[i])){
arr[i] = toupper(arr[i]);
}
}
printf("%s",arr);
return 0;
}
To measure the length of a string properly, use strlen, not sizeof
for(int i=0;i<strlen(arr);i++){ // Don't use sizeof on this line
Here's a simpler version:
#include <stdio.h>
#include <ctype.h>
int main(int argc, char *argv[]) {
char arr[100];
scanf("%s", arr);
for(int i=0;i<strlen(arr);i++){
arr[i] = toupper(arr[i]);
}
printf("%s",arr);
return 0;
}
Or even:
#include <stdio.h>
#include <ctype.h>
int main(void) {
char arr[100];
scanf("%s", arr);
for(char* c=arr; *c=toupper(*c); ++c) ;
printf("%s",arr);
return 0;
}
You are missing an include #include <ctype.h>
Also you don't need your if statement. toupper takes care of that internally (if you really want to keep islower remove the int in your if statement).
Add the header that declares islower and toupper.
#include <ctype.h>
In addiition,
if(int islower(arr[i])){
is not right. Remove the int.
if(islower(arr[i])){
whats wrong here?
The line: if(int islower(arr[i])){ fails compile for bad expression.
Change to: if(islower(arr[i])){
And in this line in your code may be looking beyond where it should:
for(int i=0;i<sizeof(arr);i++){
as you may be looking at space past the string terminator:
|s|t|r|i|n|g|\0|<unknown contents here, part of your legal memory, but are not part of the string>
it should be:
int len = strlen(arr);
for(int i=0;i<len;i++){

Struggling with strings. What is wrong with my function?

I am trying to write a small function to trim left spaces from a string, but I cannot get it right. In this version, I get the following error:
bus error: 10
Could anyone please explain to me what I am doing wrong? I am not looking so much for an alternative piece of code, but would like to understand the errors in my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void trim_string(char *);
int main(int argc, char *argv[]) {
char *temp = " I struggle with strings in C.\n";
trim_string(temp);
printf("%s", temp);
return 0;
}
void trim_string(char *string) {
char *string_trimmed = "";
int i=0, j=0;
while (isblank(string[i])) {
i++;
}
while (string[i] != '\0') {
string_trimmed[j] = string[i];
i++;
j++;
}
string_trimmed[j] = '\0';
strcpy(string, string_trimmed);
}
I have now found a workaround solution, shown below. But I am still not very clear about what I did wrong in the first place:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_LENGTH 100
void trim_string(char [MAX_LENGTH]);
int main(int argc, char *argv[]) {
char temp[MAX_LENGTH] = " I struggle with strings in C.\n";
trim_string(temp);
printf("%s", temp);
return 0;
}
void trim_string(char string[MAX_LENGTH]) {
char string_trimmed[MAX_LENGTH];
int i=0, j=0;
while (isblank(string[i])) {
i++;
}
while (string[i] != '\0') {
string_trimmed[j] = string[i];
i++;
j++;
}
string_trimmed[j] = '\0';
printf("c\n");
strcpy(string, string_trimmed);
}
Both string and string_trimmed point to string literals, here in main:
char *temp = " I struggle with strings in C.\n";
^
|
This is a string literal
temp points to a string literal and the standard says you are not allowed to modify them.
In the function trim_string you are modifying a them which is undefined behavior of which a bus error is one possible result, although anything can happen.
string_trimmed either needs to be an array like this:
char string_trimmed[n] ;
where n is the size of your input using strlen(string) would probably make sense or dynamically allocated via malloc which you would need to free at the end of your function. The same things goes for your input from main, this would work as a substitute:
char temp[] = " I struggle with strings in C.\n";
For completeness sake, the draft C99 standard section 6.4.5 String literals paragraph 6 says (emphasis mine):
It is unspecified whether these arrays are distinct provided their elements have the
appropriate values. If the program attempts to modify such an array, the behavior is
undefined.

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)

Resources