Balázs Sipos Balázs Sipos - 1 month ago 4
C Question

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

So my problem is here:

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


I couldn't find the answer maybe because it's too easy or I'm just lame.

Answer

As I mentioned in the comment, you need to allocate memory for "input". Probably this is what you are trying to do.

#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

    scanf("%s", input);

  /*
     Your code.
  */

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