前言:为了JNI,学习C/C++基础,现在是C系列。书籍来源《C语言程序设计》
心理话,为了缩短和公司里工作了3年的大神的差距,不得不想办法提升自己。
1.函数
没什么可说的,简单的函数求幂。
2.参数的传值调用
我们来看个列子
/* power: raise base to n-th power; n >= 0; version 2 */
int power(int base, int n)
{
int p;
for (p = 1; n > 0; --n)
p = p * base;
return p;
}
其中参数n用作临时变量,并通过随后执行for循环语句递减,直到其值为0,这样就不需要额外引入变量i;power函数内部对n的任何操作
不会影响到调用函数中的n的原始参数值。
当然我们可以让韩式能够修改主调用函数中的变量。这种情况下,调用者需要向被调用者函数提供待设置值的变量的地址(地址就是志向变量的指针)
,而被调用函数则需要将对应的参数声明为指针类型,并通过它间接访问变量。
如果是数组参数,情况不同。当把数组名用作参数时,传递给函数的值是数组其实元素的位置或地址(它并不是复制数组元素本身),在被调用中
可以通过数组小标访问或修改数组元素的值。
3.字符数组
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line length */
/* print the longest input line */
int getline(char line[], int maxline);
void copy(char to[], char from[]);
main()
{
int len; /* current line length */
int max; /* maximum length seen so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* longest line saved here */
max = 0;
while ((len = getline(line, MAXLINE)) > 0)
if (len > max) {
max = len;
copy(longest, line);
}
if (max > 0) /* there was a line */
printf("%s", longest);
return 0;
}
/* getline: read a line into s, return length */
int getline(char s[], int lim)
{
int c, i;
for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
4.外部变量与作用域
int getline(void);
void copy(void);
/* print longest input line; specialized version */
main()
{
int len;
extern int max;
extern char longest[];
max = 0;
while ((len = getline()) > 0)
if (len > max) {
max = len;
copy();
}
if (max > 0) /* there was a line */
printf("%s", longest);
return 0;
}
/* getline: specialized version */
int getline(void)
{
int c, i;
extern char line[];
for (i = 0; i < MAXLINE - 1
&& (c = getchar() != EOF) && c != '\n'; ++i)
line[i] = c;
if (c == '\n') {
line[i] = c;
++i;
}
line[i] = '\0';
return i;
}
/* copy: specialized version */
void copy(void)
{
int i;
extern char line[], longest[];
i = 0;
while ((longest[i] = line[i]) != '\0')
++i;
}
先暂时写这么多。