how to persist the pointer increment - c

I have the following code
void fun(int * d)
{
d+=1;
}
int main()
{
int * f=malloc(5);
f[0]=0;f[1]=1;f[2]=2;f[3]=3;f[4]=4;
fun(f);
printf("value : %d\n",*f);
return 0;
}
So, i pass an integer pointer to function and increment it there. I want that increment to persist when it returns to main.
When I print the value, The output is '0'. But I want the output to be '1' as I have incremented the value in function.
So, briefly, my question is, how to persist the changes made to a pointer?

Assuming you want to increment the pointer, not the value, you have two options:
recast the function to void fun(int ** d), use (*d)+=1; in the function body, and call using fun(&f);
recast the function to int* fun(int* d), and return the new value.
If you want to increase the value, then use (*d)+=1; in the function body.
You don't need the parentheses around *d: I've put them in for clarity.

You forgot * in d+=1;
When you pass that pointer you have access to f[0] with that approach:
Take a look here:
#include <stdio.h>
#include<stdlib.h>
void fun(int *d){
*d+=1;
}
int main(void){
int i;
int *f=malloc(5 * sizeof int);
f[0]=0;f[1]=1;f[2]=2;f[3]=3;f[4]=4;
for(i=0;i<5;i++){
printf("%d ",f[i]);
}
printf("\n");
fun(f);
for(i=0;i<5;i++){
printf("%d ",f[i]);
}
free(f);
return 0;
}
Output:
0 1 2 3 4
1 1 2 3 4
Or if you try to add +1 to all elements you can do something like this:
#include <stdio.h>
#include<stdlib.h>
int *fun(int *d, int len){
int i;
int *newArray = d;
int newValue = 1;
printf("\n");
for(i = 0; i < len; i++) {
newArray[i] += newValue;
}
return newArray;
}
int main(void){
int i;
int f[] = {0,1,2,3,4};
int *newArray;
f[0]=0;f[1]=1;f[2]=2;f[3]=3;f[4]=4;
for(i=0;i<5;i++){
printf("%d ",f[i]);
}
printf("\n");
newArray = fun(f,5);
for(i=0;i<5;i++){
printf("%d ",newArray[i]);
}
return 0;
}
Output:
0 1 2 3 4
1 2 3 4 5
And by the way you forgot to free f.

You have to pass the address of the pointer, so:
void fun(int **val) {
*val++;
....
}
int main() {
...
fun(&f);
...
}

Related

How do I get two different outputs from adding and removing a print statement? [duplicate]

This question already has answers here:
Why is it safer to use sizeof(*pointer) in malloc
(3 answers)
What happens if I use malloc with the wrong size?
(4 answers)
Closed 2 years ago.
Here is my code with the print statement followed by its output.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int *myF(int a[],int s, int n);
int *myFunc(int x[],int size,int nnum) {
int i;
size += 1;
int *y = malloc(size);
for(i=0;i<size;i++) {
if(i==0)
*y = nnum;
else {
*(y+i) = x[i-1];
printf(" %d",*(y+i)); // <-- ***THIS THING RIGHT HERE***
}
}
return y;
}
int main (int argc, char *argv[]) {
int i;
int x[7] = {1,2,3,4,5,6,7};
int *P = myFunc(x,7,12);
for(i=0;i<8;i++) {
if(i==0) printf("\n");
printf(" %d",*(P+i));
}
return 0;
}
OUTPUT:
1 2 3 4 5 6 7
12 1 2 3 4 5 6 7
(The second matrix is what I want the code to output)
Here is my code without the print statement followed by its output.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int *myF(int a[],int s, int n);
int *myFunc(int x[],int size,int nnum) {
int i;
size += 1;
int *y = malloc(size);
for(i=0;i<size;i++) {
if(i==0)
*y = nnum;
else {
*(y+i) = x[i-1];
// printf(" %d",*(y+i)); <-- ***THIS THING RIGHT HERE*** commented out
}
}
return y;
}
int main (int argc, char *argv[]) {
int i;
int x[7] = {1,2,3,4,5,6,7};
int *P = myFunc(x,7,12);
for(i=0;i<8;i++) {
if(i==0) printf("\n");
printf(" %d",*(P+i));
}
return 0;
}
OUTPUT:
12 1 2 3 4 5 83 0
(This is not what I want...)
Can somebody please explain where this code is pulling 83 and 0 for the last two elements in the array just because I chose to include or exclude a random print statement?
Any help would be greatly appreciated because I can't understand how C is pulling numbers out of thin air like this.
Your malloc size is not correct and causes undefined behavior.
The actual memory size is the length of array * size of array type.
The printf in main is actually printing something random in the memory.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int *myF(int a[],int s, int n);
int *myFunc(int x[],int size,int nnum) {
int i;
size += 1;
//int *y = malloc(size * sizeof(int) );
int *y = malloc(size );
for(i=0;i<size;i++) {
if(i==0)
*y = nnum;
else {
*(y+i) = x[i-1];
printf(" %d",*(y+i)); // <-- ***THIS THING RIGHT HERE***
}
}
return y;
}
int main (int argc, char *argv[]) {
int i;
int x[7] = {1,2,3,4,5,6,7};
int *P = myFunc(x,7,12);
for(i=0;i<8;i++) {
if(i==0) printf("\n");
printf(" %d",*(P+i));
}
free(P);
return 0;
}
If you're interesting in why printf changed the behavior, this post has in-depth explanation.
Also don't forget to free P in the end.

C changing variable and array value [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
At first code a[0] becomes 31 but in the second one a still 55. Can someone explain me the difference? What is the difference between changing a variable's and array's value in a function?
#include <stdio.h>
int h(int x[]);
int main()
{
printf("Hello, World!\n");
int a[0] = 55;
h(a);
printf("%d", a[0]);
return 0;
}
int h(int x[]) {
x[0] = 31;
}
#include <stdio.h>
int h(int x);
int main()
{
printf("Hello, World!\n");
int a= 55;
h(a);
printf("%d", a);
return 0;
}
int h(int x) {
x = 31;
}
And What about this code? This array is changed. I am really confused.
#include <stdio.h>
int h(int x[], int length);
int main()
{
int i;
int a[]= {5, 5, 5, 5};
h(a, 4);
printf("Array After Function Call\n");
for(i = 0; i < 4; i++) {
printf("%d ", a[i]);
}
return 0;
}
int h(int x[], int length) {
int i;
for(i = 0; i < length; i++) {
x[i] += x[i];
}
printf("Array in Function\n");
for(i = 0; i < length; i++) {
printf("%d ", x[i]);
}
printf("\n");
return 0;
}
And any decent book should have mentioned that arguments to functions are passed by value, meaning the value in the call is copied into the local function argument variable.
Modifying this local variable will only modify the local copy, not the value used in the call to the function.
One can overcome this problem by emulating pass by reference, which is done by passing a pointer to the variable:
void f(int *x)
{
*x = 123; // Dereference the pointer, to set the value of where it's pointing
}
int main(void)
{
int a = 0;
f(&a); // Pass a pointer to the variable a
}
This is really what's happening in the first program you show, you pass a pointer, and modify the value of where the pointer is pointing (the zero-sized array notwithstanding).
It seems that one of your major confusions is about your "array" argument.
When you declare a function as
void f(int a[]);
you don't actually declare an array argument: The compiler will treat it as a pointer and parse it as
void f(int *a);
Another point is that when you use array indexing, like
x[i] += x[i];
you are actually dereferencing the pointer, and write the values to the memory where the pointer is pointing. In fact, for any pointer or array x and index i, the expression x[i] is exactly equal to *(x + i).

Why can't I pass and edit this array to a function?

My previous question was answered but I have another in the same vein. Why does the code not work when I try to use a multi-dimensional array?
void change(int *);
int main(void){
int array[1][2] = {2};
printf("%d", array[1][2]);
change(array);
printf("%d", array[1][2]);
}
void change(int *array){
array[1][2] = 4;
}
You need to use asterisks for parameter at the time of declaration and definition.
For making array[0]=4, you only need to assign 4 to array[0] without asterisk. So your code should be:
void change(int *);
int main(void){
int array[1] = {2};
printf("%d", array[0]);
change(array);
printf("%d", array[0]);
}
void change(int *array){
array[0] = 4;
}
enter code here void change(int*);
int main(void){
int array[1] = {2};
printf("%d\n", array[0]);
change(array);
printf("%d\n", array[0]);
}
void change(int* array)
{
array[0] = 4;
*(array + 0) = 4;
}
don't put '&' in array. it is pointer. so you must change your function "change(int ...) to change(int* )"
and to change array[0] you don't need to put * on array. it's an array!. or to use * . then you must add n-th element number.
C language uses pass by value.
So, You have to receive the address of array as argument.
void change(int *, int);
int main(void) {
int array[3] = { 1, 2, 3 };
printf("%d", array[1]);
change(array, 1);
printf("%d", array[1]);
}
void change(int *array, int index) {
*(array+index) = 4;
}
For the multi dimension, You should pass a size of column.
I made 2 samples as change and change2.
I think you can understand change well.
But, In case of change2, array has a head address of memory in array[2][3] and it has 6 integers by 2x3. So, you can calculate.
void change(int array[2][3], int, int, int);
void change2(int *, int, int, int, int);
int main(void) {
int array[2][3] = { { 1, 2, 3 }, {4, 5, 6} };
printf("%d", array[1][1]);
change(array, 1, 1, 10);
printf("%d", array[1][1]);
change2((int *)array, 3, 1, 1, 20);
printf("%d", array[1][1]);
}
void change(int array[2][3], int row, int col, int value) {
array[row][col] = value;
}
void change2(int *array, int size_col, int row, int col, int value) {
*(array + row*size_col + col) = value;
}

Pass by reference in c array

Hi i want to ask about why i need to use printf("\n%d",x); instead of printf("\n%d",*x);?
Thank you very much
#include<stdio.h>
#include<stdlib.h>
#define totalnum 8
void display(int **);
int main()
{
int marks[totalnum]={55,65,75,85,90,78,95,60};
printf("The marks of student A are:");
display(marks);
return 0;
}
void display(int *x)
{
int i;
for(i=0;i<totalnum;i++)
printf("\n%d",x);
}
There is no pass by reference in C. The array decays to a pointer in the display function which you declared wrongly as int ** instead of int * - Compiler should have given you a warning at least about this:
http://ideone.com/R3skNj
This is how your display function should be like:
void display(int *x)
{
int i;
for(i = 0; i < totalnum; i++) {
printf("\n%d",*(x+i)); // or printf("\n%d",x[i]);
}
}
I think your looking for something like this:
#include <stdio.h>
#include <stdlib.h>
#define totalnum 8
void display(int *); //Typ is 'int *' NOT 'int **'
int main() {
int marks[totalnum] = {55,65,75,85,90,78,95,60};
printf("The marks of student A are:");
display(marks);
return 0;
}
void display(int *x) {
int i;
for(i = 0; i < totalnum; i++) {
printf("\n%d",*x); //Prints the value
x++; //increments the pointer
}
}

Passing array to function using pointer

I'm trying to print array of pointer using pointer instead of array but I got this error Segmentation fault at runtime:
enter number of element:5
array[0]=1
array[1]=2
array[2]=3
array[3]=4
array[4]=5
Segmentation fault
This is the code:
#include <stdio.h>
#include <stdlib.h>
int *array;
int n;
void input(int *array,int n);
void display(int *array,int n);
int sum(int *array,int n);
int main (void) {
int result;
printf("enter number of element:");scanf("%d",&n);
input(array,n);
display(array,n);
result=sum(array,n);
printf("sum of array=%d",result);
return 0;
}
void input(int *array,int n){
int j;
array=(int *)malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);scanf("%d",array+j);
}
}
void display(int *array,int n){
int j;
for(j=0;j<n;j++)
printf("%d\t",*(array+j));
printf("\n");
}
int sum(int *array,int n){
int sum=0,j;
for(j=0;j<n;j++)
sum+=*array+j;
return sum;
}
How can I fixed this code? please somebody explain me what's wrong with that code.
Variable array is a local variable in function input.
As such, it is pointless to set it with array = ..., because this assignment takes effect only inside the function. You should typically pass its address (&array) to any function that needs to change it.
In your specific example, you also have a global variable array, so a quick solution to your problem would be to simply call function input without passing variable array as an argument:
void input(int n)
{
...
array = (int*)malloc(n*sizeof(int));
...
}
int main()
{
...
input(n);
...
}
Note that this is a "dirty" workaround, and you should typically strive to avoid the use of global variables.
To add the clean version to barak's answer:
int input(int ** array, const size_t n)
{
int result = 0;
assert(NULL != array);
(*array) = malloc(n * sizeof(**array));
if (NULL == (*array))
{
result = -1;
}
else
{
size_t j;
for(j = 0; j < n; ++j)
{
printf("array[%zu]=", j);
scanf("%d", (*array) + j); /* still missing error checking here . */
}
}
return result;
}
And call it like this:
if (-1 == input(&array, n))
{
perror("input() failed");
exit(EXIT_FAILURE);
}
Try this input():
void input(int **array,int n){
int j;
*array=(int *)malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);scanf("%d",*array+j);
}
}
Because C use pass-by-value, if you want to change the value of a variable in a function, you need to pass the address of that variable as the argument to that function.
In this case, you want to change the value of array in input() and the type of array is int *, therefore the prototype of input() should be something like void input (int **array, ...).
this should do..make sure you understand what the others have said..
#include <stdio.h>
#include <stdlib.h>
int *array;
int n;
void input(int **array,int n);
void display(int **array,int n);
int sum(int **array,int n);
int main (void) {
int result;
printf("enter number of element:");scanf("%d",&n);
input(&array,n);
display(&array,n);
result = sum(&array,n);
printf("sum of array= %d",result);
return 0;
}
void input(int **array,int n){
int j;
*array= malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);
scanf("%d",(*array)+j);
}
}
void display(int **array,int n){
int j;
for(j=0;j<n;j++){
printf("%d\t",*((*array)+j)); // you can use array notation aswell
//array[0][j] will work
}
printf("\n");
}
int sum(int **array,int n){
int sum=0,j;
for(j=0;j<n;j++){
sum += *((*array)+j);
}
return sum;
}
What does *array + j do? Does it evaluate *array and add j to it? Or does it add j to array and then dereference it? Would you be willing to bet $100 on it if I told you you are wrong?
Make your life and the life of anybody reading your code easier by using parentheses, or even better, write array [j].

Resources