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

int main(){
    char *array[3];
    scanf("%s",----);   // The input is james.
    return 0;
}

How can I store james in array[1] taking james as input so that it is equivalent to array[1] = "james"; ?. So the problem is that I have to take few strings as input and then I want to store it in an array such that it is stored like I have done array[1] = "James";

Please provide a code if possible.

unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
Ram Sharma
  • 59
  • 1
  • 2
  • 10
  • First you need to allocate memory for `array[1]` to point to, then you simply use `array[1]` as the target argument for `scanf`. How to do this should be explained in every [good beginners book](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list). – Some programmer dude Jul 11 '17 at 08:49
  • I'm Surprised there isn't an existing already answered question covering this – Chris Turner Jul 11 '17 at 09:27
  • Possible duplicate of [Reading a string with scanf](https://stackoverflow.com/questions/5406935/reading-a-string-with-scanf) – Balaji Jul 11 '17 at 09:47

2 Answers2

4

You probably want something similar to this:

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

int main() {
  char array[3][10];  // array of 3 strings of at most 9 chars
  scanf("%s", array[0]);
  scanf("%s", array[1]);

  printf("%s\n%s\n", array[0], array[1]);
  return 0;
}

Or by allocating memory dynamically:

int main() {
  char *array[3];

  array[0] = (char*)malloc(10);  // allocate space for a string of maximum 9 chars
  array[1] = (char*)malloc(10);  // allocate space for a string of maximum 9 chars

  // beware: array[2] has not been initialized here and thus cannot be used

  scanf("%s", array[0]);
  scanf("%s", array[1]);

  printf("%s\n%s\n", array[0], array[1]);
  return 0;
}

Disclaimer: there is absolutely no error checking done here, for brevity. If you enter a string of more than 9 characters, the behaviour of this program will be undefined.

Anticipating the next question: inspite of reserving space for 10 chars we can only store string of maximum length of 9 chars because we need one char for the NUL string terminator.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
2

What you should do is scanf("%s", array[1]); but since array[1] is a non-init pointer, you should first malloc() it with array[1] = malloc(length_of_your_string_plus_NUL_char);

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

int main(){
char *array[3];
array[1] = malloc(100);   // I used a large number. 6 would suffice for "James"
scanf("%99s", array[1]);   // The input is james. Note the "99" (string width) addition that ensures you won't read too much and store out of bounds
return 0;
}
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124