-
Newbie Question
Hello All
Ive finally made the jump to C++ and im struggling
with the basics
Ive done loads of class stuff with PHP and the
crossover to C++ is going well, but im falling
down on the other stuff
Ive read loads of documentation about passing
chars around, declaring pointers etc, but i need
some sound advice on the best way to declare
pass and return chars from functions, ive read so
many conflicting views about this, anyone know
the best method
Marky_Mark
-
Depends on if you are talking about static memory or dynamic memory. It is important to be aware of the scope of the variables and whether the variable exists on a function stack or else on a global free store.
-
I would like to know how i could pass a function
a string or a reference to a string have that
function modify it and return it
C++ is so much more memory based than what ive
been used to, i am finding declaring and using
char pointers difficult, if i want to pass a
string to a function and return it, do i use a
pointer or a reference
Marky_Mark
-
Code:
#include<stdio.h>
void Function(int [],int);
int main()
{
int array[3];
for(int i=0; i < 3; i++)
{
array[i] = i;
printf("Before: %d\n",array[i]);
}
Function(array,i);
for(i=0; i < 3; i++)
{
printf("After: %d\n",array[i]);
}
return 0;
}
void Function(int a[],int size)
{
for(int i=0; i<size;i++)
{
a[i] +=10;
}
}
In this case the values are updated in main. The value array decays into a pointer to the first element. As in &array[0]
-
Troll_King im impressed, but i need an example
using strings
If i pass a string do i have to use an array to
access each character, or can i use one var
or pointer to access and alter that string
I need to pass a string as a whole object or
reference to that object add a char to the end
of the string and return it
Marky_Mark
-
Code:
#include<stdio.h>
#include<string.h>
void Function(char []);
int main()
{
char array[30] = { "Hello Worl"};
printf("Before: %s\n",array);
Function(array);
printf("After: %s\n",array);
return 0;
}
void Function(char a[])
{
char *ptr = a;
ptr += strlen(a);
*ptr = 'd';
}
Just make sure these is a '\o' at the end of your strings. Sometimes you have to add it. For example:
*ptr = '\0';
-
Thanks Troll_King you are a *star
:D
Marky_Mark