將二維陣列視為一維處理,找最大值及其一維索引,再轉換為行列號。
#include <stdio.h>
int max_arr(int *b, int *p1, int *p2, int n); // 聲明
int main() {
int a[3][4], *ptr, i, j, max, maxi, maxj;
for (i = 0; i < 3; i++)
for (j = 0; j < 4; j++)
scanf("%d", &a[i][j]);
ptr = a[0]; // 指向二維陣列首元素
max_arr(ptr, &max, &maxi, 12); // 12 = 3*4
maxj = maxi % 4; // 每行 4 個元素,求列
maxi = maxi / 4; // 求行
printf("max=%d, maxi=%d, maxj=%d", max, maxi, maxj);
return 0;
}
int max_arr(int *b, int *p1, int *p2, int n) {
int i;
*p1 = b[0]; // 最大值
*p2 = 0; // 最大值在一維陣列中的索引
for (i = 1; i < n; i++)
if (b[i] > *p1) {
*p1 = b[i];
*p2 = i;
}
}
字符陣列名即字符串起始位址。指標指向字符串:
char str[20], *p = str;
gets(str);
printf("%s\n", p); // 等同 printf("%s\n", str);
\0 結尾,字符陣列長度應大於字符串長度 1\0 時,%s、puts 輸出會越界錯誤
#include <stdio.h>
int main() {
char str[10], *p = str;
int i;
scanf("%s", str); // 輸入長度可能超過 10
for (i = 0; i < 10; i++)
printf("%c", *p++); // 逐字符輸出:正確
printf("\n");
p = str;
printf("%s", p); // 字符串輸出:若無 \0 會出錯
puts(str); // 同樣出錯
return 0;
}
#include <stdio.h>
int main() {
char str1[30], str2[20], *ptr1 = str1, *ptr2 = str2;
printf("input str1: "); gets(str1);
printf("input str2: "); gets(str2);
printf("str1-------str2\n%s.......%s\n", ptr1, ptr2);
while (*ptr2) *ptr1++ = *ptr2++; // 複製直到 \0
*ptr1 = '\0'; // 添加結束標誌
printf("str1-------str2\n%s.......%s\n", str1, str2);
return 0;
}
while (*ptr2) *ptr1++ = *ptr2++;:先檢查 *ptr2 是否為 \0(0 為假),非零則執行複製並後移指標。
#include <stdio.h>
int main() {
char str1[50], str2[20], *ptr1 = str1, *ptr2 = str2;
printf("input str1: "); gets(str1);
printf("input str2: "); gets(str2);
printf("str1-------str2\n%s.......%s\n", ptr1, ptr2);
while (*ptr1) ptr1++; // 移至 str1 末尾
while (*ptr2) *ptr1++ = *ptr2++; // 連接 str2
*ptr1 = '\0'; // 結束標誌
ptr1 = str1; ptr2 = str2; // 重置指標
printf("str1---------str2\n%s.......%s\n", ptr1, ptr2);
return 0;
}