[英]Why is my program crashing when I try to print a char pointer
因此,对于我的C类,我有此程序,它可以使您知道字符串中某个数字位置的字符。
char charAt( char * string, int position );
int main( int argc, char * argv[ ] ) {
int pos = atoi( argv[3] );
if( strcmp( argv[1], "charAt" ) == 0 )
{
printf( "%s", charAt( argv[2], pos ) );
}
}
char charAt( char *string, int position ){
int count = 0;
while( count != position ){
string++;
count++;
}
return *string;
}
当我编译时,使用以下命令在命令行中运行它不会显示任何错误
name charAt string 3
崩溃于
printf( "%s", charAt( argv[2], pos) );
那条线为什么当我将char指针传递给printf函数时,它会崩溃?
您在引用argv
没有检查argc
是否足够高以允许这些引用。 如果argc
只有1
怎么办?
真正的问题是使用%s
显示单个字符。 那应该是%c
。 使用%s
会将其视为字符指针 ,实际上不是,将使您的程序陷入未定义的行为之中 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.