繁体   English   中英

为什么此C程序无法正常运行?

[英]Why does this C program not function properly?

此C程序将字符串“ 1 2 3 4 5 6 7 8 9 10”拆分为令牌,将其存储在buf ,并打印buf的内容。

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

/* Fills an array with pointers to the tokens of the given string.
 * string: A null-terminated char*
 * buf: A buffer to be filled with pointers to each token. 
 */
void get_tokens(char * string, char ** buf) {
    char tmp[100];
    strncpy(tmp, string, 100);
    char * tok = strtok(tmp, " \n");
    int i = 0;
    while (tok != NULL) {
        buf[i] = tok;
        tok = strtok(NULL, " \n");
        i++;
    }
}

int main() {
    char ** buf = malloc(10 * sizeof(char*));
    char * string = "1 2 3 4 5 6 7 8 9 10";
    get_tokens(string, buf);

    int i;
    for (i = 0; i < 10; i++) {
        printf("  %s\n", buf[i]);
    }
}

输出:

  1
  2
  3
  4
   s�c8
  �c8
  8

  9
  10

为什么我的输出被破坏了?

数组tmp是具有自动存储持续时间的函数的本地数组。 函数退出后销毁。 因此,所有指向数组元素的指针都将变为无效。

我可以建议以下解决方案

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

size_t get_tokens( char ** buf, size_t n, const char *string ) 
{
    char tmp[100];
    strncpy( tmp, string, 100 );
    tmp[99] = '\0';

    size_t i = 0;
    char * tok = strtok( tmp, " " );

    while ( i < n && tok != NULL ) 
    {
        buf[i] = malloc( strlen( tok ) + 1 );
        strcpy( buf[i++], tok );
        tok = strtok( NULL, " " );
    }

    return i;
}

int main( void ) 
{
    const size_t N = 10;

    char ** buf = malloc( N * sizeof( char * ) );
    char * string = "1 2 3 4 5 6 7 8 9 10";

    size_t n = get_tokens( buf, N, string );

    for ( size_t i = 0; i < n; i++ ) 
    {
        puts( buf[i] );
    }

    for ( size_t i = 0; i < n; i++ ) free( buf[i] );
    free( buf );

    return 0;
}

程序输出为

1
2
3
4
5
6
7
8
9
10

至于您的程序,那么至少您应该使用存储说明符static声明该数组。

例如

static char tmp[100];
^^^^^^
strncpy( tmp, string, 100 );
tmp[99] = '\0';
^^^^^^^^^^^^^^^

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM