Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

debugging pointers to array elements in C?

include <stdio.h>

#include <stdlib.h>

const int one[2] = {1, 2};

int *p1;

p1 = &one[0];

int main(void)

{

printf("%d", p1);

char ch = getchar();

return 0;

}

/*

what i'm trying to do is use a pointer to refer to elements in an array. really just to mess around and try to understand and learn how to use pointers...i've basically avoided them for the whole year i've been teaching myself C (>_>)

anyways i've been hitting my head off the wall with these compile time errors:

warning: data definition has no type or storage class|

error: conflicting types for ‘p1’|

previous declaration of ‘p1’ was here|

warning: initialization makes integer from pointer without a cast|

error: initializer element is not computable at load time|

*/

Update:

in my source file...i didn't leave out the preprocessor like i did here...that was a copypasta mistake.

3 Answers

Relevance
  • oops
    Lv 6
    1 decade ago
    Favorite Answer

    Three things

    1. You can't make assignments (or perform any other instructions) outside of functions, unless you do it as part of a declaration, like this:

    int *p1 = &one[0];

    2. You can't assign a pointer to non-const data to point to const data. So, just throw another const in there:

    const int *p1 = &one[0];

    Note that this doesn't make p1 itself const, it makes the data pointed to treated as const, so:

    int x;

    p1 = &x; // legal

    *p1 = 5; // not legal

    p1[0] = 10; // not legal

    3. See mhnd_79

    4. Optional. Instead of this:

    const int *p1 = &one[0];

    You can just do this:

    const int *p1 = one;

    It's the same thing. Since, in reality, an array is just a pointer to the first element. Which is why you can also index a pointer as if it's an array, like this:

    printf("%d",p1[0]);

  • 1 decade ago

    p1 is a pointer to int variable as defined int *p1

    so printf will print out the address in the memory

    you need to use

    printf("%d",*p1)

    you can use

    p1 = one;

    as well as the array variable "one" is a pointer to the first element in the array

  • ?
    Lv 4
    4 years ago

    *ptr 865ccb4ab0e063e5caa3387c1a8741s continually go865ccb4ab0e063e5caa3387c1a8741ng to be one hundred and one. in case you prefer to get the offset from the beg865ccb4ab0e063e5caa3387c1a8741nn865ccb4ab0e063e5caa3387c1a8741ng of the array, you ought to subtract ptr from the element pos865ccb4ab0e063e5caa3387c1a8741t865ccb4ab0e063e5caa3387c1a8741on &array[i] and get the offset.

Still have questions? Get your answers by asking now.