Register for your free account! | Forgot your password?

Go Back   elitepvpers > Coders Den > C/C++
You last visited: Today at 22:17

  • Please register to post and access all features, it's quick, easy and FREE!

 

Pointer as return-value of a function

Reply
 
Old   #1
 
elite*gold: 15
Join Date: Jul 2010
Posts: 3,889
Received Thanks: 1,142
Pointer as return-value of a function

hey guys,

i am trying to write a function where i convert a string of numbers to their ASCII-equals

i know that a function can only have 1 return value which is why i want/need to have a pointer as a return value to return the whole string.

i know that i need a pointer but i have no clue how to write the function.

Code:
int *stoi(char str[]) {
	int z;
	int g = 0;

	for (z = 0; str[z] != '\0'; z++) {
		g = ctoi(str[z]);
		str[z] = g;
	}

	return str;
}
this is the ctoi function:
Code:
int ctoi(char c) {
	int i = 0;

	i = c - '0';

	return i;
}
this is the code i have for the function.
i want to call the function like this:
Code:
char *str = "-211";
	int *x;
	x = stoi(str);
	printf("\n%i \n", *x);
	return EXIT_SUCCESS;
and as you see i want to output the string into the console, but it just stays empty.

i am using eclipse-c++ on ubuntu linux



.Scy is offline  
Old   #2
 
elite*gold: 192
Join Date: May 2009
Posts: 2,227
Received Thanks: 3,256
Code:
int *stoi(char str[], int size){
     int* arr = (int*)malloc(size*sizeof(int));
     
     for(int i = 0; i < size && str[i] != '\0'; i++){
          arr[i] = (int)str[i];
     }

     return arr;
}
Code:
const char sample[] = "abcdef";
int *sample_arr = stoi(sample, sizeof(sample) / sizeof(sample[0]);
if there are any questions, just ask.


Logtetsch is offline  
Thanks
1 User
Old   #3
 
elite*gold: 15
Join Date: Jul 2010
Posts: 3,889
Received Thanks: 1,142
Quote:
Originally Posted by Logtetsch View Post
Code:
int *stoi(char str[], int size){
     int* arr = (int*)malloc(size*sizeof(int));
     
     for(int i = 0; i < size && str[i] != '\0'; i++){
          arr[i] = (int)str[i];
     }

     return arr;
}
Code:
const char sample[] = "abcdef";
int *sample_arr = stoi(sample, sizeof(sample) / sizeof(sample[0]);
if there are any questions, just ask.
i do understand that code and it helped me alot, thanks for that.

now my problem is, that it only outputs the first ascii-value e.g. '-211' comes out as 45 when i use this:
Code:
printf("test\n%i \n", *sample_arr);
the result i hoped for is:
45504949
.Scy is offline  
Old   #4
 
elite*gold: 192
Join Date: May 2009
Posts: 2,227
Received Thanks: 3,256
fixed some errors.

Code:
#include <stdio.h>
#include <stdlib.h>
 
int *stoi(const char str[], int size){
     int* arr = (int*)malloc(size*sizeof(int));
 
     for(int i = 0; i < size && str[i] != '\0'; i++){
          arr[i] = (int)str[i];
     }
 
     return arr;
}
Code:
int main(void) {
 
	const char sample[] = "-211";
	int *sample_arr = stoi(sample, sizeof(sample) / sizeof(sample[0]));
 
	for(int i = 0; i < sizeof(sample) / sizeof(sample[0]); i++)
		printf("val (%c) = %i \n", sample[i], sample_arr[i]);
 
	return 0;
}


Logtetsch is offline  
Thanks
1 User
Old   #5
 
elite*gold: 58
Join Date: Jun 2008
Posts: 2,311
Received Thanks: 8,417
Can we at least mention, that the return value of your stoi function has to be manually freed?
And "sizeof(sample)" only returns the correct value, since it's hardcoded. Don't try this on a dynamic array, like user input or something like that

Padmak
Padmak is offline  
Thanks
1 User
Old   #6
 
elite*gold: 15
Join Date: Jul 2010
Posts: 3,889
Received Thanks: 1,142
Quote:
Originally Posted by Padmak View Post
Can we at least mention, that the return value of your stoi function has to be manually freed?
And "sizeof(sample)" only returns the correct value, since it's hardcoded. Don't try this on a dynamic array, like user input or something like that

Padmak
Code:
int stoi(char str[]) {
	int base = 10; 
	int sign = 0;
	int y, x = 0, i = 0;
	if (str[0] == '-') { 
		sign = 1;
		i++;
	}
	if (str[i] == '0') { 
		base = 8;
		i++;
		if (str[i] == 'x') {
			base = 16;
			i++;
		}
	}
	for (; str[i] != 0; i++) {
		y = ctoi(str[i]);
		if (y < 0 || y >= base) {
			printf("Invalid char %c\n", str[i]);
			return EXIT_FAILURE;
		}
		x = base * x + y;
	}
	if (sign) {
		x = -x;
	}
	return x;
}
this is the code i ended up using/writing, since i needed it as an int and not a string, which i totally failed to understand when reading the task.

also i'd like to know how i interrupt my programm as soon as someone enters an invalid char.

and while we are already at it, i want to remove the 0's at the start of the arry an example:
Code:
Number int:1 as Binary: 0000000000000001
should look like this:
Code:
Number int:1 as Binary: 1
at the moment i just put spaces for the 0's so it looks like this
Code:
Number int:1 as Binary:                1
any ideas on how to achieve what i want? ^^

Edit:
i figured out a way to remove the 0's, it's not a good looking way but it works

now i am just looking for a way to stop the programm if the input was invalid(a good looking way instead of an if that checks the returns)
.Scy is offline  
Old   #7
 
elite*gold: 0
Join Date: May 2015
Posts: 625
Received Thanks: 400
You could change the signature to
Code:
int stoi(char str[], int *result)
and then set result to the integer, and return 0 on failure or something else on success. This way, you don't have to sacrifice one integer value for an error code. Right now, you can't parse #EXIT_FAILURE.

Another approach for error handling is GError from glib (other libraries provide similar functionality): Keep the result as return value, but pass another double pointer **err as argument. The caller must set *err to NULL before calling. If the function succeeds, *err is unchanged; otherwise the function sets it something else (an instance of the error structure). This way, you can provide more specific feedback, or even some kind of stack trace (e.g, add a field "cause" to your error structure).
Link:

If you really want to terminate the program within stoi, you should use exit(). However, that is really bad design. An utility function should never terminate the program; a program should be able to handle malformed user input.


algernong is offline  
Thanks
1 User
Reply



« Previous Thread | Next Thread »

Similar Threads
Visual Studio - Rad Studio ASM Function Return
#Solved.
4 Replies - C/C++
std::function of a function returning an std::function
Nun muss ich nach langer Zeit auch mal wieder einen Thread erstellen, weil mir Google nicht mehr weiterhelfen kann. Ich verzweifle an Folgendem...
19 Replies - C/C++
Running Function 2 after Function 1 finished
Hey, its me again. Im stuck on a problem since yesterday and as much as i hate to ask for help, i really dont know what else to try. I want...
3 Replies - AutoIt
ASM Funktion in C als Function Pointer schreiben
Hallo, ich bin gerade dabei, eine reverste ASM Funktion in C als Function Pointer zu schreiben. Die Funktion: CPU Disasm Address Hex dump ...
5 Replies - C/C++



All times are GMT +1. The time now is 22:17.


Powered by vBulletin®
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
SEO by vBSEO ©2011, Crawlability, Inc.

Support | Contact Us | FAQ | Advertising | Privacy Policy | Abuse
Copyright ©2017 elitepvpers All Rights Reserved.