Hey,
given that code:
0 gets printed out. Why? I think my intension is clear.Code:void call(int *a) { a = malloc(1 * sizeof(int)); a[0] = 1; } int main() { int *k; call(k); printf("%d", k[0]); return 0; }
Hey,
given that code:
0 gets printed out. Why? I think my intension is clear.Code:void call(int *a) { a = malloc(1 * sizeof(int)); a[0] = 1; } int main() { int *k; call(k); printf("%d", k[0]); return 0; }
Last edited by Salem; 06-02-2019 at 11:04 AM. Reason: Removed crayola
The 'a' at line 1 is a 'pass by value' copy of the pointer k at line 11.
You need to write something like
k = call();
or
call(&k);
if you want the call function to actually update the variable in main.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Do you realize that that pointer is being passed by value? This means that any changes to the pointer will be lost when the function returns and in this case creates a memory leak.
Ahh, pass by value of course. Thank you.
But what to do if you want to pass a whole array like this. (Secondary return type)
Last edited by SuchtyTV; 06-02-2019 at 11:26 AM.
What array are you talking about? I don't see any arrays in your code.But what to do if you want to pass a whole array like this.
See here: 'Untitled Post' | TextUploader.com
Perhaps you need to increase your compiler warning levels and fix all warnings and errors?
||=== Build: Debug in chomework (compiler: GCC 8-1) ===|
main.c||In function ‘main’:|
main.c|20|warning: ‘a_lengths’ is used uninitialized in this function [-Wuninitialized]|
main.c|22|warning: ‘b_lengths’ is used uninitialized in this function [-Wuninitialized]|
main.c|24|warning: ‘c_lengths’ is used uninitialized in this function [-Wuninitialized]|
||=== Build finished: 0 error(s), 3 warning(s) (0 minute(s), 0 second(s)) ===|