C/Pointer/Pointer Array
Содержание
Arrays and pointers
#include <stdio.h>
void main()
{
char multiple[] = "I am a string";
printf("\nThe address of the first array element : %p", &multiple[0]);
printf("\nThe address obtained from the array name: %p\n", multiple);
}
Arrays and pointers: char array
#include <stdio.h>
void main()
{
char s[] = "another string";
printf("\nAddress of second element: %p", &s[1]);
printf("\nValue of s+1 : %p\n", s+1);
}
Arrays and pointers: char array index
#include <stdio.h>
void main()
{
char s[] = "another string";
printf(" first element: %p\n", s);
printf(" second element: %p\n", s + 1);
printf(" third element: %p\n", s + 2);
}
Arrays and pointers taken further
#include <stdio.h>
void main()
{
char s[] = "a string";
printf("\n value of second element: %c\n", s[1]);
printf("value of s after adding 1: %c\n", *(s + 1));
}
Declare a pointer to an array that has 10 ints in each row: allocate memory to hold a 4 x 10 array
#include <stdio.h>
#include <stdlib.h>
int pwr(int a, int b);
int main(void)
{
int (*p)[10];
register int i, j;
p = malloc(40 * sizeof(int));
if(!p) {
printf("Memory request failed.\n");
exit(1);
}
for(j = 1; j < 11; j++)
for(i = 1; i < 5; i++)
p[ i - 1][j - 1] = pwr(j, i);
for(j = 1; j < 11; j++) {
for(i = 1; i < 5; i++)
printf("%10d ", p[i-1][j-1]);
printf("\n");
}
return 0;
}
/* Raise an integer to the specified power. */
pwr(int a, int b)
{
register int t=1;
for(; b; b--) t = t*a;
return t;
}
Two-Dimensional arrays and pointers
#include <stdio.h>
void main()
{
char twoD[3][3] = { {"1","2","3"},
{"4","5","6"},
{"7","8","9"}
};
printf("address of twoD : %p\n", twoD);
printf("address of twoD[0][0] : %p\n", &twoD[0][0]);
printf("but what is in twoD[0] : %p\n", twoD[0]);
}