c - 如何将 char 指针放入 {C} 中 for 循环中的数组 char 中

标签 c arrays pointers char

所以我的问题在这里:

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;
}

我找不到答案,也许是因为它太简单了,或者是我很蹩脚。

最佳答案

正如我在评论中提到的,您需要为“输入”分配内存。也许这就是您正在尝试做的事情。

#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.
}

关于c - 如何将 char 指针放入 {C} 中 for 循环中的数组 char 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40193803/

相关文章:

这可能是对齐内存问题吗?

python - 如何在numpy中反转子数组?

c++ - 删除后将 C++ 指针初始化为零?

c++ - 如何在C++中循环遍历具有不同长度的动态2D数组

c - 当我多次使用 fork() 时,我的程序不会停止

c - 这里发生了什么事?指针数学搞砸了?

java - 带有 switch 语句的基本数组

arrays - 在 pngs 上循环运行 ffmpeg 以提高效率?

c - 乘以指针所指向的内容

数组段错误中的 c 错误