请帮忙,这么简单的我都不懂。都不好意思问了。 # gcc -c twof2.c twof2.c: In function `main': twof2.c:3: warning: initialization from incompatible pointer type # cat twof2.c main() { int a[2][3],*p=a; int i,j; for(i=0;i<2;i++) for(j=0;j<3;j++) scanf("%d",p+i*3+j); for(i=0;i<2;i++) { printf("\n"); for(j=0;j<3;j++) printf("%10d",*(p+i*3+j)); } }
# 只是个警告,因为a是int [2][3],编译器告诉你这里可能有问题,如果你知道自己确实要这么做就没有问题,可以不理它。 从你的程序来看没什么问题,不过你既然都用了两个循环,干脆用a[i][j]算了,比指针好看多了 I am also learning C, and I am not a professional. The following is one of the homework for last week. It may help a bit on how pointer works. This program check a list of word from a file for palindromes (正讀反讀都一樣的詞). Pointers are very useful when pass data in between functions. Also give me some comment please. 代码: #include <stdio.h>
int readFile(char *, char **);
void palindromeCheck(char *);
int main (void)
{
char *palindromeList, filename[255] = '};
/* ask user for the filename */
printf("\nPlease enter the filename of your Palindrome list.\n"
": ");
scanf("%s", filename);
/* read the word list into memory */
if (readFile(filename, &palindromeList))
exit(1);
putc('\n', stdout);
/* chck each word for palindrome */
palindromeCheck(palindromeList);
return 0;
}
void palindromeCheck(char *buffer)
{
int palindrome;
char *firstChr, *lastChr, *endLine;
firstChr = endLine = buffer;
/* loop until end of file */
while (*firstChr != EOF)
{
palindrome = 1;
/* find the last character */
while (*endLine != '\n')
putc(*(endLine++), stdout);
lastChr = endLine - 1;
/* palindrome compair */
while ( (firstChr != lastChr) && ((firstChr + 1) != lastChr) )
if (*(firstChr++) != *(lastChr--))
palindrome = 0;
firstChr = ++endLine;
/* display result */
printf(" %s a palindrome\n", (palindrome)? "is":"is not");
}
}
int readFile(char *filename, char **buffer)
{
unsigned int count = 0;
FILE *fptr;
if ( (fptr = fopen(filename, "r")) == NULL )
{
fprintf(stderr, "Error Openning Source Code File %s!\n", filename);
return 1;
}
/* get the size of the file for memory allocation.
* read the file onec and count the character make
* the code protable.*/
while (getc(fptr) != EOF)
count++;
rewind(fptr);
/* allocate memory */
*buffer = malloc(count * sizeof(char));
/* read in the word list and echo them to stdout */
puts("\nReading Palindrome List From File:");
count = 0;
while ( (*(*buffer + count) = getc(fptr)) != EOF)
putc(*(*buffer + count++), stdout);
fclose(fptr);
return 0;
} |
Data File "test.dat" 代码: anna
pip
+-*-+
world
sky
same
ga1ag |
Run Log: Please enter the filename of your Palindrome list. : test.dat Reading Palindrome List From File: anna pip +-*-+ world sky same ga1ag anna is a palindrome pip is a palindrome +-*-+ is a palindrome world is not a palindrome sky is not a palindrome same is not a palindrome ga1ag is a palindrome |