p[][]
不是字符串的双数组,而是字符的双数组。它有 5 行和 5 列,如下所示:
p[row][column] =
Row| Column -> |
v | 0 | 1 | 2 | 3 | 4 |
| 0 | | | | | |
| 1 | | | | | |
| 2 | | | | | |
| 3 | | | | | |
| 4 | | | | | |
第一个scanf()
在 i = 1, j = 1 时调用,并复制字符串“hello”,p[][]
如下所示('\0' 是终止字符串的 NUL 字符):
| 0 | 1 | 2 | 3 | 4 |
| 0 | | | | | |
| 1 | | H | e | l | l |
| 2 | o |\0 | | | |
| 3 | | | | | |
| 4 | | | | | |
下次调用时,i = 1, j = 2:
| 0 | 1 | 2 | 3 | 4 |
| 0 | | | | | |
| 1 | | H | h | i |\0 |
| 2 | o |\0 | | | |
| 3 | | | | | |
| 4 | | | | | |
你可以这样写的一种方法:
#include <stdio.h>
#define MAX_CODE_LEN 80 /* or something */
int main(void)
{
char *code[5][5] = {0},
currentCode[MAX_CODE_LEN] = {0};
int day = 0,
codeNum = 0;
/* start loops at 0 */
for ( day = 0; day < 5; day++ ) {
for ( codeNum = 0; codeNum < 5; codeNum++ ) {
int len = 0;
printf("\nInput Product code %d of day %d: ", codeNum, day);
scanf("%s", currentCode);
/* len doesn't include NUL but malloc needs it */
len = strlen(currentCode);
/* yoda style so compiler catches assignment instead of equality */
if ( 0 == len ) {
/* if the user didn't enter a code move onto the next day */
code[day][codeNum] = NULL;
break;
}
len = len >= MAX_CODE_LEN? MAX_CODE_LEN - 1: len;
code[day][codeNum] = malloc(len * sizeof(char) + 1);
strcpy(code[day][codeNum], currentCode);
}
}
for ( day = 0; day < 5; day++ ) {
for ( codeNum = 0; codeNum < 5; codeNum++ ) {
if ( NULL == code[day][codeNum] ) {
/* no more codes for today */
break;
}
printf("\n\tProduct code %s day %d", code[day][codeNum], day);
}
}
return 0;
}