首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

新手!指针的指针的题出现的有关问题

2012-04-19 
新手求助!指针的指针的题出现的问题C/C++ code#include stdlib.h#include stdio.h#include string.h

新手求助!指针的指针的题出现的问题

C/C++ code
#include <stdlib.h>#include <stdio.h>#include <string.h>int main ( void )    {    void sort_string ( char **q ) ;    char *p[5] = { "China" , "America" , "India" , "Philippines" , "Canada" } ;    char **q = p ;    sort_string ( q ) ;    for ( q = p ; q - p < 5 ; q ++ )    {        puts ( *q ) ;    }    printf ( "\n" ) ;    system ( "pause" ) ;    return EXIT_SUCCESS ;}void sort_string ( char **q )    {    int i , j ;    char temp[80] ;    for ( j = 0 ; j < 4 ; j ++ )        for ( i = 0 ; i < 4 - j ; i ++ )    {            if ( strcmp ( *( q + i ) , *( q + i + 1 ) ) > 0 )    {                strcpy ( temp , *( q + i ) ) ;                strcpy ( *( q + i ) , * ( q + i + 1 ) ) ;                strcpy ( * ( q + i + 1 ) , temp ) ;            }        }}



源代码如上,运行结果也没问题,题的意思是用指针的指针解决字符串排序的问题。

可运行完以后结果就不正常了,正常来讲应该是排序完之后的结果,再\n一行之后出现"press any key to continue...",结果在这一行字前面又加了"nes"三个字母,看起来是Philippines的尾三个字母,不知道为什么会出现这种情况?

请高手解答,是什么原因造成此问题的出现,一般如何避免??

[解决办法]
你的代码在VS2010和VS11里都是一样:根本无法正确运行。原因是试图写入存储在只读区的字符串空间。

既然你都有用指针数组来指向那些字符串,那还用得着再去做strcpy?直接交换这些指针不就把字符串的位置给换了嘛!
C/C++ code
#include <stdlib.h>#include <stdio.h>#include <string.h>int main ( void )    {    void sort_string ( char **q ) ;    char *p[5] = { "China" , "America" , "India" , "Philippines" , "Canada" } ;    char **q = p ;    sort_string ( q ) ;    for ( q = p ; q - p < 5 ; q ++ )    {        puts ( *q ) ;    }    printf ( "\n" ) ;    system ( "pause" ) ;    return EXIT_SUCCESS ;}void sort_string ( char **q )    {    int i , j ;    char *temp ;    for ( j = 0 ; j < 4 ; j ++ )        for ( i = 0 ; i < 4 - j ; i ++ )    {            if ( strcmp ( *( q + i ) , *( q + i + 1 ) ) > 0 )    {                temp=*( q + i ) ;                *( q + i )= *( q + i + 1 ) ;                *( q + i + 1 )=temp;            }        }} 

热点排行