c - 在 C 中使用 strtok()

标签 c arrays strtok

<分区>

char* path = (char*)malloc(size); // path = "abc/def/ghi\0"

char** savearr1 // no malloc
char* savearr2[100]; // no malloc

这种情况,我用strtok(savearr1 or savearr2, "/");

/*  if I start this code1 */
while(...) // strtok loop
    strtok(savearr1[i], "/")

/* if I start this code2 */
while(...) // strtok loop
    strtok(savearr2[i], "/")

code1 while-loop 是段错误, code2 while-loop 成功完成

我有疑问为什么 code1 是段错误。 strtok 中的 char*[] 和 char** 行为是否不同?

这是代码,

int makeFile(const char* fname, FileType type){
    char* path = (char*)malloc(strlen(fname)+1);
    char* fnames[PATH_LEN];

    memcpy(path, fname, strlen(fname));
    path[strlen(fname)] = '\0';
    int num = 0;
    int ino;

    fnames[num++] = strtok(path, "/");
    while(fnames[num++] = strtok(NULL, "/"));

    if(strcmp(fnames[0], "") == 0) return -1;
    if(num == 2){
       makeEntry(pFileSysInfo->rootInodeNum, fnames[0], type);
    }
    else{
        ino = findEntry(pFileSysInfo->rootInodeNum, fnames[0]);
        for(int i=1; i<num-2; i++)
            ino = findEntry(ino, fnames[i]);
        makeEntry(ino, fnames[num-2], type);
    }
    free(path);
}

我将 char* fnames[PATH_LEN] 更改为 char** fnames,在 fnames[num++] = strtok(path, "/") 中出现段错误; while(fnames[num++] = strtok(NULL, "/"));

最佳答案

根据你的代码,我假设你从未初始化 char** savearr1 的大小,所以它指向 NULL 元素,当你尝试用它做一些事情(比如 printf)时,你会得到一个 segfault 即使 strtokNULL 参数没有问题。这是一个代码示例,说明您应该如何使其正常工作,它既不完美也不完整,只是一个示例。

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


int main(){
  int size = 5; // size of your path string
  int n = 5; // size of your string array
  char* path =  malloc(sizeof(char)*size);
  sprintf(path,"c/a/");
  char** arr1 = malloc(n * sizeof(char*));
  arr1[0] = path;
  int i = 0;
  char* token;
  // iterate over your string array
  for( i = 0; i < n; i++){
    // take your first string to tokenize
    token = strtok(arr1[i],"/");
    while(token != NULL){
      printf("%s\n",token);
      // keep tokenizing on arr1[i]
      token = strtok(NULL,"/"); 
    }
  }

  return 0;
}

关于c - 在 C 中使用 strtok(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50196822/

相关文章:

c - 在c中标记字符串数组

c - 解释如何仅使用这两行 : 在 C 中为二维数组分配和释放内存

c - Pair Sum - 固定总和,多个子数组

c++ - 如何将 char 数组解析为整数?

javascript - 使用选择的项目创建新对象

c - 删除 char 数组中的第一个标记并将其余部分保留在 C 中

c - 改变 C 指针的值后释放它

c - __attribute__ ((__aligned__)) 不适用于静态变量

java - 为什么我的阵列不起作用?

c - 为什么段错误? strtok 和 malloc