Home > Back-end >  Problem with storing value in pointer address
Problem with storing value in pointer address

Time:12-07

I managed to put the value in the pointer while in the function, However when i come back to the main i just dont get the values. Where am i wrong? sending parameters wrong? wrong allocation? Here's the code:

bool wc(int* nlines, int* nwords, int* nchars)
{
    int lines=5,chars=6,words=7;
    nchars = (int *) malloc(chars*sizeof(int));
    *nchars = chars;
    nlines = (int *) malloc(lines*sizeof(int));
    *nlines = lines;
    nwords = (int *) malloc(words*sizeof(int));
    *nwords = words;

}
int main() {
    int* chars; int* words; int* lines;
    int res = wc(&lines,&words,&chars);
    printf("%d %d %d\n",chars,lines,words);
    return 0;
}

CodePudding user response:

If all you want to do is be able to set 3 int values inside a function then this is how I would so it.

#include <stdio.h>
#include <stdbool.h>
 
bool wc(int* nlines, int* nwords, int* nchars)
{
    int lines=5,chars=6,words=7;
    *nchars = chars;
    *nlines = lines;
    *nwords = words;
    return true;
}
int main() {
    int lines = 0;
    int words = 0;
    int chars = 0;
    int res = wc(&lines,&words,&chars);
    printf("%d %d %d\n",chars,lines,words);
    return 0;
}

If for some reason you must use pointers as shown in your example then this will do what you want.

#include <stdio.h>
#include <stdbool.h>
 
bool wc(int** nlines, int** nwords, int** nchars)
{
    int lines=5,chars=6,words=7;
    *nchars = malloc(sizeof(int));
    **nchars = chars;
    *nlines = malloc(sizeof(int));
    **nlines = lines;
    *nwords = malloc(sizeof(int));
    **nwords = words;
    return true;
}
int main() {
    int* chars; int* words; int* lines;
    int res = wc(&lines,&words,&chars);
    printf("%d %d %d\n",*chars,*lines,*words);
    free(chars);
    free(words);
    free(lines);
    return 0;
}

As you can see this just means you need to add a bunch more * all over the place.

CodePudding user response:

In C function input variables are passed by value, not reference. So when you assign them locally, the value in the caller scope is unaffected. E.g.

void foo(int a) {
  a = 5;
}

int main() {
  int b = 3;
  foo(b);
  // here, b is still 3
}

This is exactly what you are doing in your example, though your variables are not int, but int*.

If your input variable is a pointer though, you can change the memory that the variable points to, and this will obviously reflect in the calling scope. E.g.

void foo(int *a) {
  *a = 5;
}

int main() {
  int b = 3;
  foo(&b);
  // here, b is 5
}

In your case, you want to allocate pointers, so you want your function signature to be a pointer to a pointer. E.g.

void foo(int **a) {
  *a = malloc(sizeof(int));
}

int main() {
  int* b = NULL;
  foo(&b);
  // here, b is allocated to a valid heap area
  free(b);
}
  • Related