I intend to make my pointer print the value, but it just stops working (no error report from the MinGW) . . .
#include<stdio.h>
void point_here(int *yolo) {
int you = 2014;
yolo = &you;
}
main () {
int *punk = NULL;
point_here(punk);
printf("Punk # %d is not dead\w/.\n", *punk);
}
How do I make this work? And why this does not work? Please explain. I'm new to pointers and C, and still confuse after reading stuff.
C is "call by value"; functions get copies of the caller's values, not references to them. If you change an argument inside the function, nothing happens in the caller's context.
To work around this you need explicit pointers, but even you still can't have a pointer to a local variable inside a function persist beyond the running of that function.
You're passing NULL as an argument to a function which effectively doesn't nothing. Then you try to dereference that NULL pointer which is illegal.
This modified version of your code works well:
#include <stdio.h>
void point_here(int *yolo) {
*yolo = 2014;
}
int main () {
int value = 0;
int *punk = &value;
point_here(punk);
printf("Punk # %d is not dead\w/.\n", *punk);
return 0;
}
As others have said, you have the following issues:
Pointer to a function value doesn't work after the function finishes executing
You aren't passing the pointer to the pointer you are passing the pointer value. (In other words, you aren't editing what you think you are).
I fixed these two issues by passing in a pointer that has already been allocated, then you just modify it in the function. This is one standard way to use pointers. Best of luck!
There are 2 problems. First the pointer variable is pass by value, second the variable "you" is on stack which gets lost once the function returns.
Change the variable you to static like
static int you = 2014;
and change the argument to **yolo;
Related
I'm looking to try and pass a char array from one function to another. The array seems to pass into the second function, but the contents of the array seem to be lost, apart from the first element? To get round this I tried duplicating the content of the passed array into a new local array in the called function, but this then opened up the issue of passing the new array back to the original calling function and assigning it's value back to the originally passed in array.
It's likely my pointers could be completely wrong, I'm still getting to grips with pointers in C so have been following tips from the IDE until it stops throwing errors.
Here is how I'm calling the function:
wordCheck(charIn, randWord, currentWordStatus);
The array to be updated/modified is the currrentWordStatus array.
This is the content of the array when it is passed into the function:
And here is how it actually ends up in the function:
Here is the code of my called function:
void wordCheck(char guess, char *wordToGuess, char *currentWordStatus) {
int wordLen = strlen(wordToGuess);
char wordArr[wordLen];
strcpy(&wordArr[0], wordToGuess);
bool found = false;
for (int i = 0; i < wordLen; i ++) {
printf("%c \n", (char)wordArr[i]);
if ((char) wordArr[i] == guess) {
found = true;
currentWordStatus[i] = guess;
}
}
}
I was wondering what I'm doing wrong, I'm hoping to modify the function directly as it is passed 'By Reference' (I'm aware it's a pointer to the start of the array), instead of having to remake the array inside of the function and passing it back.
Hopefully that makes some sort of sense?
Many Thanks
In the function all you really have is a pointer to the first element of the array. The program (or the compiler, and as you noticed not even the debugger) doesn't really know what a pointer is really pointing to inside a function.
There's nothing wrong, it's just how C and arrays and pointers in C works.
I understand the premise of pointers, but I find it very annoying, and I don't get why it's considered useful;
I've learned about pointers, and the next thing I know, I start seeing bubbles, asterisks, and ampersands everywhere.
#include <stdio.h>
int main () {
int *ptr, q;
q = 50;
ptr = &q;
printf("%d", *ptr);
return 0;
}
why is this important or useful?
First, parameters passed to a function can only be primitives(int, char, long....), structs or pointers. Then if you need to pass a more complex element like an array (strings) or a function, you have to pass a reference to this element.
The second things that I can quickly think of is: parameters are always passed by "value". This means the called function only get a copy of your variable. So, modifications will only affect the copy, the original variable will remain unchanged.
If you pass a variable by "reference" with a pointer, the pointer itself is immutable but as it is a reference to the original var, any modification to the pointed element will also affect the var in the caller function.
In other words, if you want to create a function that can alter a variable, you have to pass it a pointer to that variable to achieve this.
I use sprintf() to fill my string, but when I'm not done, I found something strange, the var which names test can be modified even it is a argument, I thought it was just like a Rvalue when calling function, or here is somewhere I didn't notice, and the following is my code and output.
Thanks.
#include <stdio.h>
#include <stdlib.h>
void Encap(char str[9])
{
printf("%s\n", str);
sprintf(str, "hi e");
printf("%s\n%p\n", str, &str);
}
int main()
{
char test[9] = "ABC";
printf("%s\n", test);
Encap(test);
printf("%s\n%p\n", test, &test);
system("pause");
return 0;
}
Output
ABC
ABC
hi e
0061FF10
hi e
0061FF27
You declare an array test, and you pass it to the function Encap. Your question is a little unclear, but there are two things which may be surprising you:
Within the function Encap, you are modifying the contents of the array.
After the function Encap returns, back in the caller, the modifications to the test array persist.
(You also asked about "rvalue", which can be an important concept, but it doesn't apply here in the way that you expect.)
The reason this works the way it does is because of two different things:
When you pass the array test to the function Encap, you do not pass the entire value of the array. what actually gets passed is just a pointer to the array;s first element.
Within the function Encap, you are not modifying the pointer that was passed, instead, you are modifying the memory that the pointer points to. You are using the pointer as a value (a pointer value) to know where the memory is that you should modify -- and this ends up being the test array up in main().
You are passing pointer to function, It will surely change value at the memory location.
As you are passing pointer, another copy of pointer will be created and which will be used in function.(Whenever we call to a function, copy of variable is made and operations are done on that copy variable). Here the variable is of type pointer, hence another pointer variable will be created which will be pointing to same memory locations as pointed by test but will be having different address.
That's why two different memory address gets printed as you are printing address of two different pointers.
I have a doubt regarding passing of arrays to a function.
consider the following code snippet.
void main()
{
int a[4]={10,20,30,40};
fun1(a);
}
void fun1(int a1[])
{
for(int i=0;i<4;i++)
{
printf("%d\n",a1[i]);
}
}
Passing an array is nothing but passing the address of the first location.
And I should pass the above array with its name(starting address of the array).
My doubt is since a[4] is an auto variable, it should die when it comes out of the main function and it should give the unexpected results(the pointer should be dangled).
But it is working fine.
I am very confused with this, can you please clear it off.
Even if we pass a single element int a as f(&a), it should not exist in the function f, if it is declared as automatic(local variable in main function).
Please clear this as well.
Yes, variable a will be out of scope when main() terminates.
But when fun1 is executing, main() has not reached termination yet, so the content of a is still perfectly valid.
What you are doing is fine. The array a does indeed go out of scope but by that point your function has finished so you don't have to worry about accessing data that is no longer around. If you have concerns about passing the variable as the array name (which is fine) you can always step through your code to ensure you are accessing the data you think that you are.
You could also make your function safer by passing an additional integer argument that specifies the size of your array rather than having it hard coded as 4. If you used the function you have and passed an integer array of length less than 4, it will be accessing out of bounds memory.
void fun1 ( int a1[]) is creating a copy of whatever array is coming into the function. So it will exist.
You can also vision it as a stack. A stack will be created for main() method. And since the fun1() is called from the main method, the stack of main method will destroy only when the stack for fun1() is destroyed.
int a[] in function declaration/definition is equal to const int *a so nothing bad will happen and no memory will be freed implicitly.
int enter_path(char** path) {
char* standard = "./questions.txt";
printf("\n\t%s\n\t%s",
"Please enter the file location.", "path: ");
fgets(*path, MAX_PATH_LENGTH ,stdin);
*(*path + (strlen(*path)-1) ) = '\0';
if(**path == '\n' )
*path = strdup(standard);
return 0;
}
int main(void){
char* path = malloc(MAX_PATH_LENGTH);
enter_path(&path);
some_other_function_using_the_path_string(path);
}
the code above works fine, the reason why i'm posting this is the following.
Why do i have to pass the adress of the pointer "path" to the function enter_path, so some other function can use/read the modified value.
So in short, Why do i have to use the &-operand when calling the "enter_path" function, and can't define enter_path as "int enter_path(char* path);"
I know this is normal variables refering to datatypes like int, long, etc.
but i assumed that when working with pointers the change should be visible for every other function. cause the pointer still referes to the same point in the memory, just the value has been changed.
Could it be i'm seeing this all wrong?
PS: I'm trying my best to keep my code ansi-C compliant, which is the reason i'm using fgets instead of readline. Just sayin that cause i've allready got some comments regarding the fact that the readline function is easier/safer to use.
With kind regards,
JD
If you have a variable of type T that you want a function to be able to modify, you need to pass it via a pointer, i.e.:
void foo(T *p) { *p = 42; }
int main(void) {
T t;
foo(&t);
// The value of t is now 42
}
In your code, T is char *; in other words, your function needs to be able modify a pointer, so you need to pass it a pointer to that pointer.
However, this is not good code. If (**path == '\n') is true, then you will leak memory.
The reason is that if you specify the parameter type as char *, you will operate on a copy of the pointer in the function, so your code (modified for this scenario)
path = strdup(standard);
Would not reflect back in the caller after the function ends
By passig the address of the variable, you can change the pointed-to pointer and this change will persist even after the function returns
Think of the pointer as your data (just like with int, etc.) by passing a char * pointer you can modify the pointed-to characters; by passing a char ** pointer, you can modify the pointed-to pointer (with the modification reflecting in the caller function as well).
You are passing a variable path that is itself a pointer.
But you are modifying the pointer itself in the function enter_path, hence you will have to pass the pointer to path and hence the address of path is to be passed and hence &path is passed.
In the current scenario, the line
*path = strdup(standard);
it does modify the variable path in the function but it's value will not change outside the function, i.e. in function main.