C++ :: Returning Local Pointer
Apr 24, 2013
I hear all the time about the rule of not returning a local pointer, but I'm not exactly sure what that insinuates. Would this example be classified as violating that rule?
class Foo {
public:
Bar* ReturnBar() {
Bar* temp = &bars.at(0);
return temp;
}
private:
vector<Bar> bars;
};
View 3 Replies
ADVERTISEMENT
Aug 18, 2014
Should i never return a pointer to a local variable. i have seen the following code in the standard text book.
Code:
struct node *add_to_list(struct node *list, int n)
{
struct node *new_node;
new_node = malloc(sizeof(struct node));
// some code here
return new_node;
}
new_node is a local pointer then why is he returning the new_node? Is it wrong or am i failing to understand something?
View 2 Replies
View Related
Jul 9, 2014
I know that this code is wrong because it returns the address of local variable which no longer exist after function:
int *f1()
{
int x = 2;
return &x;
}
However, why this one does not show problem and runs fine, here the pointer p is also a local variable:
int *f2()
{
int x = 2;
int *p;
p = &x;
return p;
}
View 6 Replies
View Related
Nov 21, 2014
As the title says, i'm using a function which returns a pointer to a struct:
the struct is the following:
Code:
typedef struct POINT
{
uint16_t x;
uint16_t y;
}
Coordinate; the function i'm using:
Code:
Coordinate * Read_XTP2046(void)
{static Coordinate screen;
//calculations to determine the coordinates
screen.x=(temp[1]+temp[2])/2;
screen.y=(temp[0]+temp[2])/2;
// and so on...
return &screen;}
The question is: how do i catch this pointer and make it into a Coordinate struct in which i can read the x and y.
In my main program i would do the following:
Code:
Coordinate cor;
cor = Read_XTP2046();
This does not work, as the function returns a pointer, but how to transform this pointer into a Coordinate struct.
View 8 Replies
View Related
Mar 24, 2015
I am trying to return a char pointer so that i can re use it again. I am writing a vigenere function that takes a message, a key and an initialization vector where it performs the encryption, prints out the encrypted message and returns the encrypted message. I print out the process step by step and everything works, however i pass the answer and print it out again and only the first letter gets changed. I put my code below and my output right after that.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
void decrypt(char *to_encrypt, char *key, char* pct);
enum flag{encryption = 1, decryption = 0};
[code].....
View 3 Replies
View Related
May 29, 2014
I have a class which looks like the following:
Code:
class Gadgets {
public:
Data* GetData() const {
return _data.data();
}
const Data * GetDataConst() const {
return _data.data();
}
private:
QSharedPointer<Data> _data;
}
You may ask why i have the second GetData() method that return a pointer to my private member, which will then expose my private member externally. I provide this function just for the case where user can do the following
Code:
Gadgets * myGadgets = new Gadgets();
myGadgets->GetData()->ModifyData(.....);
My question pertains to the use of QSharedPointer of data(), where in the doc, it says
T * QSharedPointer::data () const
Returns the value of the pointer referenced by this object.
Note: do not delete the pointer returned by this function or pass it to another function that could delete it, including creating QSharedPointer or QWeakPointer objects.
Whereas, if i were to use
Code:
Data* data as my private member class instead of QSharedPointer;
I will not need to worry if the caller do as follow
Code:
Data * data = new Data();
Data *data2 = myGadgets.GetData();
data2 = data;
delete data;
View 3 Replies
View Related
Mar 5, 2013
I have a program that is trying to find all factors of an integer given. It needs to be done in a recursion function. Right now i have code similar to just getting the prime factors of a integer.
unsigned int * find_factors_using_recursion(unsigned int x ) {
unsigned int * factor = new unsigned int[];//do i put x in here ?
for(unsigned int i = 2; i < x; ++i) {
if(x % i == 0) {
find_factors_using_recursion(x / i);
*factor = (factor[i] = i);
} }
return factor;
delete [] factor;
}
When i cout the *factor = (factor[i] = i) it gives me the prime numbers of the integer passed into the function but when I return the pointer it only returns one of the prime numbers. I'm new to c++, how to return pointers from functions that would be great with an example to go with it.
View 10 Replies
View Related
Dec 10, 2014
I know how to pass a 2-D array to a function. The prototype for that is void f(int (*p)[2]) assuming the array is of integers and there are 2 columns in it.
However, if I wanted the same function to return a pointer to a 2-D array, what would be the prototype?
View 2 Replies
View Related
Jun 22, 2014
So, I've got this class in SDL Player that has, among other things, an SDL_Texture* to hold an image that represents the player on the screen. I'd assume it's good practice to do get() and set() functions for the class; but because textures are handled via pointers, when I write a get() function I end up returning a pointer to an internal resource; which isn't good practice I hear as it "breaks" encapsulation.
Find my code below:
#ifndef PLAYER_H
#define PLAYER_H
#include "SDL.h"
#include "SDL_image.h"
#include "CTexture.h"
class Player {
[Code] .....
View 1 Replies
View Related
Apr 25, 2014
I am writing a class Player which has several char arrays as private fields. I am trying to write a method which returns an array as a pointer, but doesn't alter the array in any way, thus the const.
Here is a snippet:
Code: class Player
{
private:
char state[MAX_STATE_CHAR + ONE_VALUE];
int rating;
char last[MAX_NAME_CHAR + ONE_VALUE];
char first[MAX_NAME_CHAR + ONE_VALUE];
int groupNumber = NEG_ONE;
public:
char * GetFirst() const
{
return first;
}
Visual studio is saying that the return type doesn't match.
View 3 Replies
View Related
Aug 31, 2014
Here's my code,
#include <iostream>
#include <unistd.h>
#include <thread>
using namespace std;
void Blink();
[Code] .....
The problem is i don't want to use local vars , is ther anyway do end the loop safely(removing all the vars used in function and etc) without using a local var ?
View 3 Replies
View Related
Nov 20, 2014
//Declare Variables
String lstNme, frstNme, finalGrade;
Double pointsEarned, percentage;
//Get First Name, Last Name and Score
[Code]....
I am getting the error popping up on the line 58 under the console.writeline...+finalGrade "Error1Use of unassigned local variable 'FinalGrade' The thing i am not understanding is that it is declared
View 11 Replies
View Related
Jul 28, 2014
#include<iostream>
#include<stdlib.h>
using namespace std;
int Name(),Minimum(),Maximum();
int main() {
int name=Name(),minimum= Minimum(),maximum= Maximum();
[Code] ...
There are error to let user to key in minimum and maximum values, i would like to know whats the problem?
View 1 Replies
View Related
Feb 21, 2014
i have two point P1 and P2 where i want to move P1 and P2 with keeping the distance and the position of the P2 relative to P1 i thought that when i keep the distance between the two point that involve keep in the same time the local position of P2 but when tested it does not work initial position of P1=(10.0f, 00.0f, 00.0f) initila position of P2 relative to p1 =(50,10,-8) we can get the global position of p2 ----- final position of P1 =(50,10,-8) final position of P2 in the world space =(40.31,8.06,-6.45) then we calculate the distance before and after we found that there are equal but when we calculate the position of p2 relative to p1 after and before we found that there are not equal.
how i can keep the local position and distance ?
View 14 Replies
View Related
Apr 28, 2014
I was trying to make this program using function and everything seemed to be going great....until I compiled. This is just a project I want to work on myself. It's going to be more than what it is now.
I received next errors:
Compiling...
700Dlg.cpp
E:CPP700700Dlg.cpp(65) : error C2601: 'KeyEvent' : local function definitions are illegal
E:CPP700700Dlg.cpp(106) : error C2601: 'MsgLoop' : local function definitions are illegal
E:CPP700700Dlg.cpp(115) : error C2601: 'KeyLogger' : local function definitions are illegal
E:CPP700700Dlg.cpp(142) : error C2601: 'main' : local function definitions are illegal
Error executing cl.exe.
[Code] .....
I need load keylogger code by MFC Dialog. How I can do it ?
View 7 Replies
View Related
Jul 31, 2013
Want to initialize a local one dimensional array. How can I do the same without a loop?
Found from some links that
int iArrayValue[25]={0};
will initialize all the elements to ZERO. Is it?
If yes then can we write below code to initialize the elements to a non-ZERO value?
int iArrayValue[25]={4};
Do we have some other way to initialize an array to a non-ZERO value? Memset can initialize the element to ZERO.
View 7 Replies
View Related
Feb 28, 2014
Here is my overloaded operator :
const double & Waz::operator()(int i,int j) const {
return ((WazImpl const)(*p))(i,j);
}
Where in Waz class I have : WazImpl* p; and in the class WazImpl I have an operator () const
The warning is : Warning C4172 returning address of local variable or temporary
As far as I understand I'm returning a temp variable which is destroyed somewhere else what can I do to fix it?
View 2 Replies
View Related
Jan 27, 2015
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Furniture {
class Program {
static void Main(string[] args)
[Code] ....
I tried changing the type of variable to char but i still get the same result. i also tried using a switch statement which was my first choice but i had the same issue.
View 2 Replies
View Related
Sep 7, 2014
I keep getting the "Uninitialized Local Variable" error. But for my code it's says it's the variable 'pay' in my Manager Function. This is the only error that is popping up.
I've tried setting pay to 0 but when I do, I get a bunch of external errors. I've also tried assigning pay to WeeklySalary like this:
double pay = WeeklySalary;
//Calculating pay for a company
#include <iostream>
#include <iomanip>
using namespace std;
//Function prototypes
double managerFunction();
double hourlyWorkerFunction();
double commissionWorkerFunction();
[Code] .....
View 10 Replies
View Related
Nov 15, 2014
{
//Declare Variables
decimal hrsWrkd, otPay, grossPay, taxRate=0, taxAmount, netPay,basePay, wage;
string maritalStatus;
const decimal WORKWEEK = 40;
const decimal OTRATE = 1.5m;
const double m = 0.15;
[Code] ....
The error message I am getting is Use of unassigned local variable 'otPay' . I see its been declared and been used in the code so the error is confusing, also when i run the program i noticed that it doesn't take out the taxes.
View 4 Replies
View Related
Mar 6, 2015
Code:
#include <iostream.h>
void showMenu();
void showFees (double, int);
void main()
[Code] .....
View 2 Replies
View Related
Apr 23, 2013
I have the following code. According to this the values of pointers p[0] and p[1] remains unchanged since the swap is made to local variables in swap function.Now my doubt is how can I swap the pointers p[0] and p[1] inside the function swap??
Code:
#include<stdio.h>int main(){char*p[2]={"hello","good morning"};
swap(p[0],p[1]);
printf("%s %s",p[0],p[1]);return0;
}void swap(char*a,char*b){char*t; t=a; a=b; b=t;
}
View 5 Replies
View Related
Nov 21, 2014
So I have been working my way through this assignment and I'm just stuck now. I cannot get this work properly It just tells me I'm trying to return a local variable when attempting to return postfix in the to_postfix function. It is line 97 that wont compile. Also I cannot change anything in runner.c.
Calculator.c
Code:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <ctype.h>
4 #include <string.h>
5 #include "stack.h"
[Code] .....
View 11 Replies
View Related
Apr 13, 2013
how to combine a string value with a local buffer containing time and date. I can't seem to get the syntax correct or find an example of this.
So I'll have a result like: The time is: 12:49 04/13/2013. My project will put different values in String mess1 depending on what's happening.
My code
char buf1[20];
String mess1 = "The time is:";
sprintf(buf1, "%02d:%02d %02d/%02d/%4d", hour(), minute(), month(), day(), year());
//mySerial.println(buf1); // operates perfect
mySerial.println(mess1 buf1); // Does not compile - error: expected `)' before 'buf1'
I have also tried a comma between (mess1, buf1), no dice.
View 3 Replies
View Related
Nov 29, 2014
Can I return a non-dynamic local address of a var from a function?
int* func(int m){
m=1;
return m;
}
My compiler giving warning but compiles and returns add but My tutor handout says it will not compile...!!! she used array in func and returned arr[m]
View 4 Replies
View Related
Feb 3, 2013
I got the following lines of code from a book. The variable char c is being used here to demonstration local variable declaration.
while(char c = cin.get() != 'q') {
cout << c << " wasn't it" << endl;
if(char x = c == 'a' || c == 'b')
cout << "You typed a or b" << endl;
else
cout << "You typed " << x << endl;
}
It compiles and runs. There are two issues when I try to run it.
1) It seems to loop through two times for every entry. If I insert cin.ignore() just before the closing bracket, it seems to work better.
2) the variable c does not seem to have the character I entered when examined in the if statement.
What is happening with the variable c inside the while loop scope?
Does c actually get initialized?
View 2 Replies
View Related