簡體   English   中英

如何在{C}的for循環中將char指針放入數組char中

[英]How can i put a char pointer into an array char in a for loop in {C}

所以我的問題在這里:

char *input;
char *takenpositions[18] ={"A0","A0","A0" /* etc. */};

int k;

for(k = 0; k < 18; k++) {

  scanf("%s",&input);

  /* ...
     The program is doing other things with input here, then i want to put it
     into the array in place of the A0s. I tried strncpy, and other things but
     maybe i couldn't use it correctly.
     ...
  */

  takenpositions[k] = input;
}

我找不到答案,可能是因為它太簡單,或者我只是just腳。

正如我在評論中提到的,您需要為“輸入”分配內存。 可能這就是您要嘗試做的。

#define MAX_STR_LEN 256
char *input;
char *takenpositions[18] ={0}; //Initialize all pointers to NULL (0).

int k;

for(k = 0; k < 18; k++) {

    input = malloc(sizeof(char)*(MAX_STR_LEN+1)); //Allocate memory

    char scanfString[32] = ""; //32 characters should be sufficient for scanf string.

    //To limit number of character inputs use string "%<limit>s" in scanf()
    sprintf(scanfString, "%%%us", MAX_STR_LEN);


    scanf(scanfString, input);

  /*
     Your code.
  */

  takenpositions[k] = input; //Save pointer.
}

暫無
暫無

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

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