This question already has answers here:
returning a local variable from function in C [duplicate]
(4 answers)
Changing address contained by pointer using function
(5 answers)
Closed 1 year ago.
I am trying to implement a function as stated in the title. I think I am very close to solution but a problem.
input: 51% are admitted.
output: x:51 (null)
but output should have been:
s:% are admitted.
My try is here:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int str2int(int);
int isdigit(int);
long str2double(int);
int driver(char *, char *);
int main(){
char *s = "51% are admitted.";
char *sPtr;
int x = driver(s, sPtr);
printf("x:%d sPtr:%s", x, sPtr);
return 0;
}
int isdigit(int ch){
return (ch>=48 && ch<=57)?1:0;
}
int str2int(int ch){
return ch-48;
}
int driver(char *s, char *sPtr){
int i=0, number=0;
while(s[i]!='\0' && isdigit(s[i])){
number = number*10 + str2int(s[i]);
i++;
}
sPtr=s+i;
printf("%s\n", sPtr);
return number;
}
The problem is, in main, sPtr seems as null but in driver function, sPtr is % is admitted which is what it should be. How can I fix the problem so that I can print the solution correctly without using a printf statement in driver function?
EDIT:
The problem is as #Johnny Mopp said, I was trying to pass a copy of that variable. Therefore, I need to pass the address of variable of *sPtr which appears char **sPtr in prototype. And the code should be:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int str2int(int);
int isdigit(int);
long str2double(int);
int driver(char *, char **);
int main(){
char *s = "51% are admitted.";
char **sPtr;
int x = driver(s, &sPtr);
printf("x:%d sPtr:%s", x, sPtr);
return 0;
}
int isdigit(int ch){
return (ch>=48 && ch<=57)?1:0;
}
int str2int(int ch){
return ch-48;
}
int driver(char *s, char **sPtr){
int i=0, number=0;
while(s[i]!='\0' && isdigit(s[i])){
number = number*10 + str2int(s[i]);
i++;
}
*sPtr=s+i;
return number;
}
Thanks for contributes of #Johnny Mopp and #paulsm4
Related
Probably the question has already been answered, but unfortunately many many attempts didn't work for me :(
Precisely said, let's assume I have:
char buf[] = "\\x41\\x41\\x41\\x41"
Basically I want to convert it into
char con[] = "\x41\x41\x41\x41"
I tried by splitting the buf into arrays like:
buf1[]="41",buf2[]="41", buf3[]="41", buf4[]="41"
char newbuf[30];
sprintf(newbuf, "%2x%2x%2x%2x", buf1,buf2,buf3,buf4);
printf("%s:%llx:%p:%d",newbuf,newbuf,newbuf, strlen(newbuf))
and the output I get is: ffffe3f0ffffe410ffffe430ffffe450ffffe470ffffe490:7fffffffe3b0:0x7fffffffe3b0:48
But the output I wish to see is AAAA
So is there something I am missing or doing wrong?
Try this:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void parseCstring(const char buf[], char con[])
{
int i=0, j=0;
unsigned char x;
while ( (x = buf[i]) != '\0')
{
if ( (x=='\\') && (buf[i+1]=='x') && (isxdigit(buf[i+2])) && (isxdigit(buf[i+3])) )
{
unsigned int val;
sscanf(&(buf[i+2]),"%2x", &val);
x=(unsigned char)val;
i+=3;
}
con[j++]=x;
i++;
}
}
int main()
{
char buf[] = "\\x41\\x42\\x42\\x41 was great\\x21";
char con[40];
printf("%s\n",buf);
parseCstring(buf, con);
printf("%s\n",con);
return 0;
}
I am trying to run below program in an online C compiler. But I get segmentation error. Can you help me fix this
#include <stdio.h>
#include <string.h>
int main()
{
char string[15] = "Strlwr in C";
printf("%s",tolower(string));
return 0;
}
Following is the prototype of tolower
int tolower(int c);
You should pass an int or something like char which can safely convert to int. Passing char * (Type of string) like you do leads to UB.
To convert a string to lowercase, you need to convert each character separately. One way to do this is:
char string[15] = "Strlwr in C";
char lstr[15];
int i = 0;
do {
lstr[i] = tolower(string[i]);
} while(lstr[i] != '\0');
printf("%s", lstr);
You are using tolower incorrectly. This function returns int and gets int as a parameter (here is it's declaration: int tolower(int c);). What you want to do is call it on each char of your char array, and print each one:
char string[15] = "Strlwr in C";
for(int i = 0; i < strlen(string); i++)
printf("%c",tolower(string[i]));
Read cplusplus.com/reference/cctype/tolower It takes a single int as parameter, not char and not array.
You probably want to use a loop on "string", which processes each in turn.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
int i;
char string[15] = "Strlwr in C";
for (i=0; i< sizeof(string)/sizeof(char); i++)
{
string[i]=(char)(tolower((int)string[i]));
}
printf("%s\n",string);
return 0;
}
Output:
strlwr in c
This question already has answers here:
Passing address of array as a function parameter
(6 answers)
Closed 9 years ago.
I'm writing a function that gets a string, allocates memory on the heap that's enough to create a copy, creates a copy and returns the address of the beginning of the new copy.
In main I would like to be able to print the new copy and afterwards use free() to free the memory. I think the actual function works although I am not the char pointer has to be static, or does it?
The code in main does not work fine...
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int make_copy(char arr[]);
int main()
{
char arrr[]={'a','b','c','d','e','f','\0'};
char *ptr;
ptr=make_copy(arrr);
printf("%s",ptr);
getchar();
return 0;
}
int make_copy(char arr[])
{
static char *str_ptr;
str_ptr=(char*)malloc(sizeof(arr));
int i=0;
for(;i<sizeof str_ptr/sizeof(char);i++)
str_ptr[i]=arr[i];
return (int)str_ptr;
}
OK, so based on the comments. A revised version:
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
char* make_copy(char arr[]);
int main()
{
char arrr[]={"abcdef\0"};
char *ptr=make_copy(arrr);
printf("%s",ptr);
getchar();
return 0;
}
char* make_copy(char arr[])
{
static char *str_ptr;
str_ptr=(char*)malloc(strlen(arr)+1);
int i=0;
for(;i<strlen(arr)+1;i++)
str_ptr[i]=arr[i];
return str_ptr;
}
Or even better:
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char* make_copy(char arr[]);
int main()
{
char arrr[]={"abcdef\0"};
printf("%s",make_copy(arrr));
getchar();
return 0;
}
char* make_copy(char arr[])
{
char *str_ptr;
str_ptr=(char*)malloc(strlen(arr)+1);
return strcpy(str_ptr,arr);
}
You're on the right track, but there are some issues with your code:
Don't use int when you mean char *. That's just wrong.
Don't list characters when defining a string, write char arrr[] = "abcdef";
Don't scale string alloations by sizeof (char); that's always 1 so it's pointless.
Don't re-implement strcpy() to copy a string.
Don't cast the return value of malloc() in C.
Don't make local variables static for no reason.
Don't use sizeof on an array passed to a function; it doesn't work. You must use strlen().
Don't omit including space for the string terminator, you must add 1 to the length of the string.
UPDATE Your third attempt is getting closer. :) Here's how I would write it:
char * make_copy(const char *s)
{
if(s != NULL)
{
const size_t size = strlen(s) + 1;
char *d = malloc(size);
if(d != NULL)
strcpy(d, s);
return d;
}
return NULL;
}
This gracefully handles a NULL argument, and checks that the memory allocation succeeded before using the memory.
First, don't use sizeof to determine the size of your string in make_copy, use strlen.
Second, why are you converting a pointer (char*) to an integer? A char* is already a pointer (a memory address), as you can see if you do printf("address: %x\n", ptr);.
sizeof(arr) will not give the exact size. pass the length of array to the function if you want to compute array size.
When pass the array to function it will decay to pointer, we cannot find the array size using pointer.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *strdup(const char *str)
{
char *s = (char*)malloc(strlen(str)+1);
if (s == NULL) return NULL;
return strcpy(s, str);
}
int main()
{
char *s = strdup("hello world");
puts(s);
free(s);
}
Points
~ return char* inside of int.
~ you can free the memory using below line
if(make_copy!=NULL)
free(make_copy)
Below is the modified code.
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
char* make_copy(char arr[]);
int main()
{
char arrr[]={'a','b','c','d','e','f','\0'};
char *ptr;
ptr=make_copy(arrr,sizeof(arrr)/sizeof(char));
printf("%s",ptr);
printf("%p\n %p",ptr,arrr);
getchar();
return 0;
}
char* make_copy(char arr[],int size)
{
char *str_ptr=NULL;
str_ptr=(char*)malloc(size+1);
int i=0;
for(;i<size;i++)
str_ptr[i]=arr[i];
str_ptr[i]=0;
return str_ptr;
}
I want to return a character array from a function. Then I want to print it in main. how can I get the character array back in main function?
#include<stdio.h>
#include<string.h>
int main()
{
int i=0,j=2;
char s[]="String";
char *test;
test=substring(i,j,*s);
printf("%s",test);
return 0;
}
char *substring(int i,int j,char *ch)
{
int m,n,k=0;
char *ch1;
ch1=(char*)malloc((j-i+1)*1);
n=j-i+1;
while(k<n)
{
ch1[k]=ch[i];
i++;k++;
}
return (char *)ch1;
}
Please tell me what am I doing wrong?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *substring(int i,int j,char *ch)
{
int n,k=0;
char *ch1;
ch1=(char*)malloc((j-i+1)*1);
n=j-i+1;
while(k<n)
{
ch1[k]=ch[i];
i++;k++;
}
return (char *)ch1;
}
int main()
{
int i=0,j=2;
char s[]="String";
char *test;
test=substring(i,j,s);
printf("%s",test);
free(test); //free the test
return 0;
}
This will compile fine without any warning
#include stdlib.h
pass test=substring(i,j,s);
remove m as it is unused
either declare char substring(int i,int j,char *ch) or define it before main
Lazy notes in comments.
#include <stdio.h>
// for malloc
#include <stdlib.h>
// you need the prototype
char *substring(int i,int j,char *ch);
int main(void /* std compliance */)
{
int i=0,j=2;
char s[]="String";
char *test;
// s points to the first char, S
// *s "is" the first char, S
test=substring(i,j,s); // so s only is ok
// if test == NULL, failed, give up
printf("%s",test);
free(test); // you should free it
return 0;
}
char *substring(int i,int j,char *ch)
{
int k=0;
// avoid calc same things several time
int n = j-i+1;
char *ch1;
// you can omit casting - and sizeof(char) := 1
ch1=malloc(n*sizeof(char));
// if (!ch1) error...; return NULL;
// any kind of check missing:
// are i, j ok?
// is n > 0... ch[i] is "inside" the string?...
while(k<n)
{
ch1[k]=ch[i];
i++;k++;
}
return ch1;
}
Daniel is right: http://ideone.com/kgbo1C#view_edit_box
Change
test=substring(i,j,*s);
to
test=substring(i,j,s);
Also, you need to forward declare substring:
char *substring(int i,int j,char *ch);
int main // ...
I'm a beginner in C language. After reading the initial chapters of Ritchie's book, I wrote a program to generate random numbers and alphabets.
The program compiles fine with gcc. However on running it, it gives an error "Segmentation fault", which is incomprehensible to my limited knowledge. I'd be glad to understand what I've written wrong.
#include <stdio.h>
#include <stdlib.h>
#include "conio.h"
#include <time.h>
long int genrandom(int,int);
void randAlph(void);
char letterize(int);
int main (void) {
// char full[9];
// char part_non[4];
srand(time(0));
int i;
for (i=0;i<50;++i) {
randAlph();
};
}
long int genrandom(int mino,int maxo) {
int val=mino+rand()/(RAND_MAX/(maxo-mino)+1);
return val;
}
void randAlph (){
int val;
char text;
val=genrandom(0,26);
// return val;
text=letterize(val);
printf("%s ,",text);
}
char letterize(int num) {
char letter='A'+num;
return letter;
}
printf("%s ,",text); is wrong - it says that text is a nul-terminated array of chars. Use
printf("%c ,", text);
instead to print your single char.
#include <stdio.h>
#include <stdlib.h>
#include "conio.h"
#include <time.h>
int genrandom(int,int);
void randAlph(void);
char letterize(int);
int main (void) {
// char full[9];
// char part_non[4];
srand(time(0));
int i;
for (i=0;i<50;++i) {
randAlph();
};
}
int genrandom(int mino,int maxo) {//changed function return type to int
int val=mino+rand()/(RAND_MAX/(maxo-mino)+1); //Be careful when you are using '/' operator with integers
return val; //returning int here why set return type to long int?
}
void randAlph (){
int val;
char text;
val=genrandom(0,26);
// return val;
text=letterize(val);
printf("%c ,",text);//Replace %s with %c
}
char letterize(int num) { //No bound checking on num eh?
char letter='A'+num;
return letter;
}
That's all I had to say. :)
Why use %s when text is char. You dont need a string type in the function. Just a char would do. Change in the function : void randAlph ()
printf("%s ,",text);
to
printf("%c ,", text);