Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C
// CODE  1
#include <stdio.h>
int main()
{
    float cgpa[] = {25, 39, 45,95,98,9,
    9,48,45,546,8,41,4,8,84,84,95};


int *pointer = &cgpa[1];

printf("%d\n",*pointer);


      return 0;
}

Versus the below code:

C
//CODE 2
#include <stdio.h>
    int main(){ 

int a =5;
int *b=&a;
*b=8;
int d =5;
int *e= &d;
printf("The sum of a and b is %d\n", *e+*b);
printf("the addres a =%u\n",&a);
printf("the addres a =%u\n", b);
printf("the value  a =%d\n",*b);
printf("the value  a =%d\n",a);
printf("the value  b =%d\n",b);

return 0;
}


What I have tried:

I want to get the value in the variable using the pointer. In first code sample I tried to do it with array, but failed. In the second code sample I was able to execute. Why?
Posted
Updated 2-Jun-22 7:56am
v3

FIrst off, arrays in C start from a zero index, not one.
So if an array arr has three elements 101, 102, and 103 then you can only access it's content using then indexes 0, 1, and 2:
arr[0] == 101
arr[1] == 102
arr[2] == 103


Second, integers and floats are not necessarily the same size: an int is commonly 16 bits (or 2 bytes) or 32 bits (or 4 bytes) wide, while a float is generally 32 bits (4 bytes) wide. Trying to use an int pointer to access float data may or may not works at all, depending on your compiler and / or operating system!

Thirdly, floats and integers aren't stored the same way: int is stored as a "straight binary value" with the most significant bit determining if the value is positive or negative. A float is much more complicated: IEEE 754 - Wikipedia[^]

So again, using a int pointer to access a float array isn't going to give you the results you expect!

Try it like this:
C
#include <stdio.h>

int main()
    {
    float cgpa[] = {25, 39, 45, 95, 98,  9,
                     9, 48, 45,546,  8, 41,
                     4,  8, 84, 84, 95};

    float *pointer = &cgpa[0];
    printf("%0.0f\n",*pointer);

    return 0;
    }
And it'll start to work.

But ... the name of an array is a pointer to it's first element (that's defined in the language specification) so this code is both more readable and simpler:
C
#include <stdio.h>

int main()
    {
    float cgpa[] = {25, 39, 45, 95, 98,  9,
                     9, 48, 45,546,  8, 41,
                     4,  8, 84, 84, 95};

    float *pointer = cgpa;
    printf("%0.0f\n",*pointer);

    return 0;
    }
 
Share this answer
 
Get yourself a copy of The C Programming Language (2nd Edition): Amazon.co.uk: Ritchie, Dennis, Kernighan, Brian: 8601410794231: Books[^] where pointers (and all the other concepts of C) are clearly explained.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900