一个简单的C程序

来源:互联网 发布:origin图片导出数据 编辑:程序博客网 时间:2024/04/30 11:44

很久很久没有写C程序了,C++已经深入骨髓。写起C来居然还是非常吃力。

比如在C中,数组和字符串是不能互相赋值的。这可难为了。输出一个数组还要一个一个输出,

下面是一个下例子,就是将一个字符串反转。

#include <stdio.h>#include <string.h>#include <sys/socket.h>#include <arpa/inet.h>#include <unistd.h>#include <netinet/in.h>#include <stdlib.h>#define MAXLINE 1024static char revbuf[MAXLINE];void *reverse(char * buf,int len){int i,n;if(len > MAXLINE || len < 0){printf("length is error\n");}i = 0;n = len;while(i < len){revbuf[i++] = *(buf+(--n));}revbuf[i] = '\n';}int main(){char *buf = "OK,I am test";reverse(buf,strlen(buf));fwrite(revbuf,1,strlen(buf)+1,stdout);}

在不能数组跟字符串相互赋值,字符串不能当成数组用的时候,只能指针一个一个指定了。

为什么C中字符串不能当数组使用呢?

在另外一个地方似乎找到了答案:

In C arrays are non-modifiable lvalues, you can't change what they point to since they don't point anywhere in the first place.

0 0
原创粉丝点击