0

I am new to pointers. For the below program , I get an answer of 255 and not 20. Please suggest how to correct.

Here is the code :

int sum(int *a ,  int *b);
int main()
{
    int *p;
    int *q;
    *p =10;
    *q =10;
    int c = sum(p,q);
    printf("%d",c);
}
int sum(int *a , int *b)
{  
    return((*a)+ (*b));
}
5
  • I tested it here I got 20 -ideone.com/B3M43p Commented Aug 11, 2015 at 17:32
  • 1
    @ameyCU it is UB to set a pointer to an arbitrary value like 10, you could also have gotten a working packman game, although not likely Commented Aug 11, 2015 at 17:35
  • @GlennTeitelbaum Yes ofcourse it is UB I just pointed out what I got . Commented Aug 11, 2015 at 17:36
  • Incompatible integer to pointer conversion initializing 'int *' with an expression of type 'int' Commented Aug 11, 2015 at 17:40
  • I'm voting to close this question as off-topic because multi-dupped grossly-obvious pointer misuse. Commented Aug 11, 2015 at 18:27

6 Answers 6

3

There is data, then there are pointers. For simplicity, once you have data, then you can point to it. This is accomplished by using the & operator. To go back to the data from a pointer, use the * operator as you have

Something more like

int sum(int *a ,  int *b);
int main()
{
    int p_data=10;
    int q_data=10;
    int *p =&p_data;
    int *q =&q_data;
    int c = sum(p,q);
    printf("%d",c);
}
int sum(int *a , int *b)
{    
    return((*a)+ (*b));
}

EDIT: Also note that pointers can be used to access memory allocated from malloc, or mmap'd, or other means

Sign up to request clarification or add additional context in comments.

5 Comments

This can be achieved without using 2 variables ,right !!.
@ameyCU yes, but it is more concrete to have data variables and pointer variables before the abstract idea of space allocated from malloc
@gabbar is there anything else you need to answer your question?
glenn no, thnks for d support
@gabbar it is customary on Stack Overflow, if your question is answered, to chose one answer by clicking the checkmark
3

You need to alloc memory for pointers. This code should work:

#include <stdio.h>
#include <stdlib.h>

int sum(int *a ,  int *b);
int main()
{
    int *p = (int*) malloc(sizeof(int));
    int *q = (int*) malloc(sizeof(int));
    if (p != NULL && q != NULL)
    {
        *p =10;
        *q =10;
        int c = sum(p,q);
        printf("%d", c);
        free(p);
        free(q);
    }
    else
    {
         printf("Could not allocate enough memory");
         return 1;
    }

    return 0;
}

int sum(int *a , int *b)
{
    return (*a) + (*b);
}

Hope this helps!

6 Comments

if i get it right, you are just assigning p and q some random address in order to initilise the pointers.
Yes, i'm allocating the some bytes (the amount needed to represent an int) in heap memory, and then i'm storing there the value 10.
It's int main(void) at least, btw.
@gabbar calling the return from malloc a "random address" misses the point. malloc returns a pointer into memeory that has been obtained from the OS in a regimented way. What the address is, might seem random but it is logical
@DamiánMontenegro for illustration purposes, you should test the return from malloc, although unlikely at this amount of memory, it is better to train that practice
|
0

A pointer is a variable that holds the address of another variable, and this seems clear to you. But what seems not still very clear is that when you create a pointer the compiler doesn't automagically create also a variable to point to...

In code:

int *p;
int *q;
*p =10;
*q =10;

You are defining p and q as pointers to int, but to which variables of type int they point? They have a garbage inside and can point anywhere, so when assigning 10 to what they point to, in reality, you are spamming somewhere in memory.

Under these conditions when you call sum I would expect more a memory fault than a strange value (255), but everything can happen with bad pointers, even to access an existing memory.

The correct code is:

int sum(int *a ,  int *b);

int main()
{
    int i1, i2;      //Allocate 2 int variables
    int *p = &i1;    //Create pointers and assign them
    int *q = &i2;    //the address of int vars i1 and i2
    *p =10;          //Initialize variables pointed by pointers with 10
    *q =10;
    int c = sum(p,q);
    printf("%d",c);
}

int sum(int *a , int *b)
{
    return((*a)+ (*b));
}

Comments

0

A pointer needs to be assign the address of some valid memory to point to before it may be dereferenced of the *-operator and gets written some data to where it points to.

You miss those very assignments.

Dereferencing a pointer implies reading out its value. If no value ever had been assigned to a pointer variable, already reading out its value might invoke the infamous Undefined Behaviour, anything can happen after this.

So your result could also have been just the famous 42.

Lesson learned: Never apply any operator to a variable which had not been properly been initialised.

Comments

0

Another approach. I think it may be useless for return function but it can help you about pointers It is passing pointer to the sum function

#include <stdio.h>

int sum(int *a ,  int *b);
int main()
{
    int p = 10;
    int q = 10;

    int c = sum(&p,&q);
    printf("%d",c);
}
int sum(int *a , int *b)
{

    return((*a)+ (*b));
}

Comments

-2

You're getting 255 is because of random luck. I get 20 when I compile it, but that's also random luck. The technical term is "undefined behavior", and this is undefined because you never initialized your int *p and int *q pointers.

What's inside your pointer variables? You don't know, I don't know, nobody does. Since you never initialized them, their contents are whatever bits were there before initialization. It's like moving into a house and getting whatever junk the previous tenants left for you.

If the contents of the pointers are addresses in memory (and they don't overlap), then the value returned should be 20 (by random luck). But if one of them contains a null address, who knows what you'll get!

If you want to get 20 reliably, you need to allocate memory:

In C++:

int * p = new int;
int * q = new int;

In C:

int * p = (int*)malloc(sizeof(int))
int * q = (int*)malloc(sizeof(int))

5 Comments

can you pls complete your answer
I hit submit by mistake
its tagged c including C++ might be confusing
Did you tag it C, or did the OP? There's no way of knowing what language they intended if they didn't explicitly say
@JayFrizzle first, you can check edit history (I did not). Below each question there are tags, this questioin has[c] and [pointers] as tags. It is considered explicit and sufficient to have the language tag indicate language requested

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.