Saturday, February 20, 2010

Programmer - Taking user input with pointers

Programmer Question

I'm trying to get better at using pointers, and not using array notation. So I have a function to read user input and return a pointer to that array. I can do it like this and it seems to work ok:



float *GetValues(float *p, size_t n) 
{

float input;
int i = 0;

if ((newPtr = (float *)malloc(n * sizeof(float))) == NULL) {
cout << "Not enough memory\n";
exit(EXIT_FAILURE);
}
cout << "Enter " << n << " float values separated by whitespace: \n";

while (scanf("%f", &input) == 1) {
p[i] = input;
i++;
cout << *p;
}
return p;
}


But then if I do this:



float *GetValues(float *p, size_t n) 
{
float *newPtr;
float input;

if ((newPtr = (float *)malloc(n * sizeof(float))) == NULL) {
cout << "Not enough memory\n";
exit(EXIT_FAILURE);
}
cout << "Enter " << n << " float values separated by whitespace: \n";

while (scanf("%f", &input) == 1) {
*newPtr++ = input;
}
return newPtr;
}


I get just 0s entered into p. Why is that?



Also, do I have to allocate memory here for an array of size n? I first tried it with the method above using pointers and not allocating memory but just set p = to input and I was getting garbage values. Thanks!



Edited: Sorry, I allocated a new ptr and was returning the wrong one like you said. I was just trying to input the numbers into my pointer and display it back on the screen to myself and wasn't paying attention to the return type and I was getting an output of 0 when I would cout << *newPtr.

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails