简体   繁体   English

C 中的 strtok 使用 char 指针崩溃

[英]strtok in C crashes with char pointer

I have a char array in C with numbers separated by comma, and need to convert it to an int array.我在 C 中有一个 char 数组,数字用逗号分隔,需要将其转换为 int 数组。 However when I try to use strtok, it crashes with EXC_BAD_ACCESS.但是,当我尝试使用 strtok 时,它会因 EXC_BAD_ACCESS 而崩溃。 Can you help me please?你能帮我吗?

The method方法

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ARRAY_LEN (0x100)
#define OUTPUT_LEN (0x400)

unsigned int StaticAnalyze_load( char* data, char delimiter, int* array, unsigned int length ){
    char *token;
    int i=0;

    // CRASHES HERE (BAD ACCESS)
    token = strtok(data, &delimiter);

    while( token != NULL ) {
        array[i] = atoi(token);
        token = strtok(NULL, &delimiter);
        i++;
    }

    for(i=0;i<3;i++) {
        printf("%d\n", array[i]);
    }

    return length;
}

Main主要的

int main(int argc, const char * argv[]) {
      char *data =  "13,654,24,48,1,79,14456,-13,654,13,46,465,0,65,16,54,1,67,4,6,74,165,"
           "4,-654,616,51,654,1,654,654,-61,654647,67,13,45,1,54,2,15,15,47,1,54";
      int array[ARRAY_LEN]; // array, I need to fill-in with integers from the string above
      unsigned int loaded = StaticAnalyze_load(data, ',', array, ARRAY_LEN);
      return 0;
}

data in main is a pointer to a literal string that strtok cannot modify. main中的data是指向strtok无法修改的文字字符串的指针。
strchr could be used to identify the tokens. strchr可用于识别令牌。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ARRAY_LEN (0x100)
#define OUTPUT_LEN (0x400)

unsigned int StaticAnalyze_load( char* data, char delimiter, int* array, unsigned int length ){
    char *token = data;
    int i=0;

    while( i < ARRAY_LEN && token != NULL ) {
        array[i] = atoi(token);
        token = strchr(token, delimiter);
        if ( token) {
            ++token;
        }
        i++;
    }

    for(i=0;i<3;i++) {
        printf("%d\n", array[i]);
    }

    return length;
}

int main(int argc, const char * argv[]) {
    char *data =  "13,654,24,48,1,79,14456,-13,654,13,46,465,0,65,16,54,1,67,4,6,74,165,"
       "4,-654,616,51,654,1,654,654,-61,654647,67,13,45,1,54,2,15,15,47,1,54";
    int array[ARRAY_LEN]; // array, I need to fill-in with integers from the string above
    unsigned int loaded = StaticAnalyze_load(data, ',', array, ARRAY_LEN);
    return 0;
}

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

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