簡體   English   中英

將字符串拆分為字符串數組

[英]Split a string into an array of strings

一段時間以來,我還沒有用C編寫程序。我習慣於用C#編寫代碼。

因此,我想使用定界符將用戶字符串輸入拆分為字符串數組。 我這樣做了,但是當我想獲取數組時,我遇到了段錯誤。 例如,我只想打印數組的一個元素。

我已經在網上檢查過,但沒有任何效果。

有什么提示嗎?

謝謝

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

int main ()
{

  char function[] = {};
  char * pch;
  int cpt = 0;
  int nb_terms = 0;

  printf("Entrez le nombre de termes :\n");
  scanf("%d", &nb_terms);

  char word[nb_terms];

  printf("Entrez votre fonction en n'utilisant que les 5 caractères suivants (a,b,c,d et +) :\n");
  scanf("%s", &function);

  pch = strtok (function,"+");
  while (pch != NULL)
  {
    word[cpt++] = pch;
    printf ("%s\n",pch);
    pch = strtok (NULL, "+");
  }

  printf ("%s\n",&word[1]);

  return 0;

}

編譯器警告會揭示您的問題。

cc -Wall -Wshadow -Wwrite-strings -Wextra -Wconversion -std=c99 -pedantic -g   -c -o test.o test.c
test.c:7:21: warning: use of GNU empty initializer extension [-Wgnu-empty-initializer]
  char function[] = {};
                    ^
test.c:7:21: warning: zero size arrays are an extension [-Wzero-length-array]
test.c:18:15: warning: format specifies type 'char *' but the argument has type 'char (*)[0]'
      [-Wformat]
  scanf("%s", &function);
         ~~   ^~~~~~~~~

這些都是相關的。 char function[] = {}GNU擴展,用於聲明大小為0的數組 然后,您嘗試將內容放入其中,但是大小為0。因此將會出現溢出。

相反,您需要分配一些空間以function並確保將scanf限制為僅該大小,而不是更大。

// {0} initializes all characters to 0.
// 1024 is a good size for a static input buffer.
char function[1024] = {0};

// one less because of the null byte
scanf("%1023s", &function);

下一個警告...

test.c:23:17: warning: incompatible pointer to integer conversion assigning to 'char' from 'char *';
      dereference with * [-Wint-conversion]
    word[cpt++] = pch;
                ^ ~~~
                  *

是因為您試圖將字符串( char *pch放在字符( char )所在的位置。 即使您僅從strtok讀取單個字符(您不能保證),該字符始終會返回一個字符串。 您需要一個字符串數組( char ** )。 它還具有描述性的變量名。

char *word;                 // this was pch
char *words[nb_terms];      // this was word

改變后pchword ,而wordwords在它的代碼全部作品的其余部分。

  size_t word_idx = 0;
  for(
      char *word = strtok(function,"+");
      word != NULL;
      word = strtok(NULL, "+")
  ) {
      words[word_idx++] = word;
  }

我將添加有關scanf的常見警告

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM