什么东西放在厨房驱虫:大虾来,帮小弟解决个c的问题。

来源:百度文库 编辑:查人人中国名人网 时间:2024/05/02 21:35:16
我用Dev-C++编程,可是在编“测字符串长度”时遇到如下问题(不用strlen);
#include<stdio.h>
#include<string.h>
int length(char s[255])
{int i;
i=0;
strcpy(*s[1],"3");//invalid type argumentof 'unary'
printf("%c",s[1]);
while(*s[i]!="\0"){i=i+1;}//invalid type argumentof 'unary'
length=i;//invalid lvalue in assignment
}
#include<stdio.h>
#include<string.h>
int length(char s[255])
{int i;
i=0;
strcpy(&s[1],"3");
printf("%c",s[1]);
while(&s[i]!="\0"){i=i+1;}
return i;
}
main()
{char p;
printf("%d",length("abc"));
scanf("%c",&p);
}
运行时程序错误,但能编译能运行

你要注意:
1.你定义了数组,对数组元素进行使用的时候
直接用数组名加下标就行,如你的例子中定义
的数组s,想对s[1]赋值的话直接就:s[1]='3'
就行了,因为它不是指针,所以不能用*s[1]来
调用它.如果你定义的是一个指针数组,如:
char * s[256]的话,就可以用这样的方法来
调用: s[1]="3",就是让s[1]这个元素(它是
一个指针)指向常量字符串"3".
2.strcpy()函数是用来给字符串变量(数组)
拷贝赋值的,它的第一个参数必须是字符指针
(字符串首地址),它的执行结果是将第二个参数
拷贝到第一个参数提供的地址里,然后再加上一
个结束符:'\0',所以系统会提示你:");//invalid type argumentof 'unary'
即不正确的参数类型

#include<stdio.h>
#include<string.h>
int length(char s[255])
{int i;
i=0;
strcpy(&s[1],"3");
printf("%c",s[1]);
while(&s[i]!="\0"){i=i+1;}
return i;
}

#include<stdio.h>
#include<string.h>
int length(char s[255])
{
int i = 0;
strcpy(s,"3");
printf("%c",s[1]);
while(s[i]!='\0'){i=i+1;}
return i;
}