Yahoo Clever wird am 4. Mai 2021 (Eastern Time, Zeitzone US-Ostküste) eingestellt. Ab dem 20. April 2021 (Eastern Time) ist die Website von Yahoo Clever nur noch im reinen Lesemodus verfügbar. Andere Yahoo Produkte oder Dienste oder Ihr Yahoo Account sind von diesen Änderungen nicht betroffen. Auf dieser Hilfeseite finden Sie weitere Informationen zur Einstellung von Yahoo Clever und dazu, wie Sie Ihre Daten herunterladen.
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|
*/
in my source file...i didn't leave out the preprocessor like i did here...that was a copypasta mistake.
3 Antworten
- oopsLv 6vor 1 JahrzehntBeste Antwort
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]);
- vor 1 Jahrzehnt
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
- bondurantLv 4vor 4 Jahren
*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.