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.

3
  • 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. Commented Jul 11, 2017 at 8:49
  • I'm Surprised there isn't an existing already answered question covering this Commented Jul 11, 2017 at 9:27
  • Possible duplicate of Reading a string with scanf Commented Jul 11, 2017 at 9:47

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@tilz0R definitely not.
Curious that code does not use a width limit like scanf("%9s",...
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.