In this line:

scanf("%s", &word[i]);

You need to make sure word[i] is pointing somewhere, and has enough space to occupy the string entered. Since word[i] is a char * pointer, you need to at some time allocate memory for this. Otherwise, it is just a dangling pointer not pointing anywhere.

If you want to stick with scanf(), then you can allocate some space beforehand with malloc.

malloc() allocates requested memory on the heap, then returns a void* pointer at the end.

You can apply malloc() in your code like this:

size_t malloc_size = 100;

for (i = 0; i < 3; i++) {
    word[i] = malloc(malloc_size * sizeof(char)); /* allocates 100 bytes */
    printf("Enter word: ");
    scanf("%99s", word[i]); /* Use %99s to avoid overflow */
                            /* No need to include & address, since word[i] is already a char* pointer */
} 

Note: Must check return value of malloc(), because it can return NULL when unsuccessful.

Additionally, whenever you allocate memory with the use of malloc(), you must use free to deallocate requested memory at the end:

free(word[i]);
word[i] = NULL; /* safe to make sure pointer is no longer pointing anywhere */

Another approach without scanf

A more proper way to read strings should be with fgets.

char *fgets(char *str, int n, FILE *stream) reads a line from an input stream, and copies the bytes over to char *str, which must be given a size of n bytes as a threshold of space it can occupy.

Things to note about fgets:

  • Appends \n character at the end of buffer. Can be removed easily.
  • On error, returns NULL. If no characters are read, still returns NULL at the end.
  • Buffer must be statically declared with a given size n.
  • Reads specified stream. Either from stdin or FILE *.

Here is an example of how it can be used to read a line of input from stdin:

char buffer[100]; /* statically declared buffer */

printf("Enter a string: ");
fgets(buffer, 100, stdin); /* read line of input into buffer. Needs error checking */

Example code with comments:

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

#define NUMSTR 3
#define BUFFSIZE 100

int main(void) {
    char *words[NUMSTR];
    char buffer[BUFFSIZE];
    size_t i, count = 0, slen; /* can replace size_t with int if you prefer */

    /* loops only for three input strings */
    for (i = 0; i < NUMSTR; i++) {

        /* read input of one string, with error checking */
        printf("Enter a word: ");
        if (fgets(buffer, BUFFSIZE, stdin) == NULL) {
            fprintf(stderr, "Error reading string into buffer.\n");
            exit(EXIT_FAILURE);
        }

        /* removing newline from buffer, along with checking for overflow from buffer */
        slen = strlen(buffer);
        if (slen > 0) {
            if (buffer[slen-1] == '\n') {
                buffer[slen-1] = '\0';
            } else {
                printf("Exceeded buffer length of %d.\n", BUFFSIZE);
                exit(EXIT_FAILURE);
            }
        } 

        /* checking if nothing was entered */
        if (!*buffer) {
            printf("No string entered.\n");
            exit(EXIT_FAILURE);
        }

        /* allocate space for `words[i]` and null terminator */
        words[count] = malloc(strlen(buffer)+1);

        /* checking return of malloc, very good to do this */
        if (!words[count]) {
            printf("Cannot allocate memory for string.\n");
            exit(EXIT_FAILURE);
        }

        /* if everything is fine, copy over into your array of pointers */
        strcpy(words[count], buffer);

        /* increment count, ready for next space in array */
        count++;
    }  

    /* reading input is finished, now time to print and free the strings */
    printf("\nYour strings:\n");
    for (i = 0; i < count; i++) {
        printf("words[%zu] = %s\n", i, words[i]);
        free(words[i]);
        words[i] = NULL;
    }

    return 0;
}

Example input:

Enter a word: Hello
Enter a word: World
Enter a word: Woohoo

Output:

Your strings:
words[0] = Hello
words[1] = World
words[2] = Woohoo
Answer from RoadRunner on Stack Overflow
Top answer
1 of 7
12

In this line:

scanf("%s", &word[i]);

You need to make sure word[i] is pointing somewhere, and has enough space to occupy the string entered. Since word[i] is a char * pointer, you need to at some time allocate memory for this. Otherwise, it is just a dangling pointer not pointing anywhere.

If you want to stick with scanf(), then you can allocate some space beforehand with malloc.

malloc() allocates requested memory on the heap, then returns a void* pointer at the end.

You can apply malloc() in your code like this:

size_t malloc_size = 100;

for (i = 0; i < 3; i++) {
    word[i] = malloc(malloc_size * sizeof(char)); /* allocates 100 bytes */
    printf("Enter word: ");
    scanf("%99s", word[i]); /* Use %99s to avoid overflow */
                            /* No need to include & address, since word[i] is already a char* pointer */
} 

Note: Must check return value of malloc(), because it can return NULL when unsuccessful.

Additionally, whenever you allocate memory with the use of malloc(), you must use free to deallocate requested memory at the end:

free(word[i]);
word[i] = NULL; /* safe to make sure pointer is no longer pointing anywhere */

Another approach without scanf

A more proper way to read strings should be with fgets.

char *fgets(char *str, int n, FILE *stream) reads a line from an input stream, and copies the bytes over to char *str, which must be given a size of n bytes as a threshold of space it can occupy.

Things to note about fgets:

  • Appends \n character at the end of buffer. Can be removed easily.
  • On error, returns NULL. If no characters are read, still returns NULL at the end.
  • Buffer must be statically declared with a given size n.
  • Reads specified stream. Either from stdin or FILE *.

Here is an example of how it can be used to read a line of input from stdin:

char buffer[100]; /* statically declared buffer */

printf("Enter a string: ");
fgets(buffer, 100, stdin); /* read line of input into buffer. Needs error checking */

Example code with comments:

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

#define NUMSTR 3
#define BUFFSIZE 100

int main(void) {
    char *words[NUMSTR];
    char buffer[BUFFSIZE];
    size_t i, count = 0, slen; /* can replace size_t with int if you prefer */

    /* loops only for three input strings */
    for (i = 0; i < NUMSTR; i++) {

        /* read input of one string, with error checking */
        printf("Enter a word: ");
        if (fgets(buffer, BUFFSIZE, stdin) == NULL) {
            fprintf(stderr, "Error reading string into buffer.\n");
            exit(EXIT_FAILURE);
        }

        /* removing newline from buffer, along with checking for overflow from buffer */
        slen = strlen(buffer);
        if (slen > 0) {
            if (buffer[slen-1] == '\n') {
                buffer[slen-1] = '\0';
            } else {
                printf("Exceeded buffer length of %d.\n", BUFFSIZE);
                exit(EXIT_FAILURE);
            }
        } 

        /* checking if nothing was entered */
        if (!*buffer) {
            printf("No string entered.\n");
            exit(EXIT_FAILURE);
        }

        /* allocate space for `words[i]` and null terminator */
        words[count] = malloc(strlen(buffer)+1);

        /* checking return of malloc, very good to do this */
        if (!words[count]) {
            printf("Cannot allocate memory for string.\n");
            exit(EXIT_FAILURE);
        }

        /* if everything is fine, copy over into your array of pointers */
        strcpy(words[count], buffer);

        /* increment count, ready for next space in array */
        count++;
    }  

    /* reading input is finished, now time to print and free the strings */
    printf("\nYour strings:\n");
    for (i = 0; i < count; i++) {
        printf("words[%zu] = %s\n", i, words[i]);
        free(words[i]);
        words[i] = NULL;
    }

    return 0;
}

Example input:

Enter a word: Hello
Enter a word: World
Enter a word: Woohoo

Output:

Your strings:
words[0] = Hello
words[1] = World
words[2] = Woohoo
2 of 7
4

There seems to be a bit of confusion in this area. Your primary problem is you are attempting to write each word to the address of each of pointers you declare with char *word[3];. (not to mention you have no storage allocated at the location pointed to by each pointer -- but you never get there as you attempt to write to the address of each pointer with &word[i] rather than to the pointer itself)

While you can use scanf you will quickly run into one of the many pitfalls with taking user input with scanf that plague all new C programmers (e.g. failing to handle the '\n' left in the input buffer, failing to handle whitespace in strings, failing to limit the number of characters read/written, failing to validate the read or handle EOF, etc...)

A better approach is to simply use fgets and then trim the '\n' that fgets read and includes in the buffer to which it stores the string. A simple example would be:

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

#define NWDS 3    /* declare a constant for the maximum number of words */

int main (void) {

    int i, n = 0;
    char word[NWDS][50] = { "" };       /* provide storage or allocate */

    for (i = 0; i < NWDS; i++) {        /* for a max of NWDS */
        printf ("Enter word : ");       /* prompt */
        if (!fgets (word[i], sizeof word[i], stdin))  /* read/validate */
            break;                      /* protect against EOF */
        size_t len = strlen (word[i]);  /* get length */
        if (word[i][len-1] == '\n')     /* check for trailing '\n' */
            word[i][--len] = 0;         /* overwrite with nulbyte  */
    }
    n = i;                              /* store number of words read */
    putchar ('\n');                     /* make it pretty */

    for (i = 0; i < n; i++)             /* output each word read */
        printf (" word[%d] : %s\n", i, word[i]);

#if (defined _WIN32 || defined _WIN64)
    getchar();  /* keep terminal open until keypress if on windows */
#endif

    return 0;
}

Go ahead and cancel input at any time by generating an EOF during input (ctrl + d on Linux or ctrl + z on windoze), you are covered.

Example Use/Output

$ ./bin/wordsread
Enter word : first word
Enter word : next word
Enter word : last word

 word[0] : first word
 word[1] : next word
 word[2] : last word

Looks things over, consider the other answers, and let me know if you have further questions.

๐ŸŒ
Quora
quora.com โ€บ How-do-I-declare-an-array-of-strings-that-are-inputted-by-the-user-in-C
How to declare an array of strings that are inputted by the user in C - Quora
Answer (1 of 2): There are two ways, 1. Using structure for eg, struct string{ char str[100]; }STRING[100]; 2. Or by using char string[100][100]; I generally prefer using structure as it results in more cleaner code.
๐ŸŒ
W3Schools Blog
w3schools.blog โ€บ home โ€บ create array of strings in c from user input
create array of strings in c from user input - W3schools
June 27, 2022 - [ad_1] create array of strings in c from user input #include int main() { char str[5][10]; printf("enter the strings...n"); for(int i =0; i
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 73601685 โ€บ how-to-fill-array-of-strings-using-user-input
c - how to fill array of strings using user input - Stack Overflow
I am not sure if I understood your question properly, but if you want to create an array of strings and fill it one string at a time with get_string, then you can do this: #include <stdio.h> #include "cs50.h" #include <string.h> #define MAX_STRINGS 100 int main( void ) { string strings[MAX_STRINGS]; int num_strings = 0; printf( "In order to stop, please enter an empty string.\n" ); //read strings into array for ( int i = 0; i < MAX_STRINGS; i++ ) { strings[i] = get_string( "Please enter string #%d: ", i + 1 ); //determine whether string is empty if ( strings[i][0] == '\0' ) break; num_strings++; } printf( "You have entered the following %d strings:\n", num_strings ); //print all strings for ( int i = 0; i < num_strings; i++ ) { printf( "%d: %s\n", i + 1, strings[i] ); } }
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 41085282 โ€บ c-how-can-i-store-from-user-based-input-various-strings-in-an-array-inside-a
C - How can I store (from user-based input) various strings in an array inside a structure? - Stack Overflow
So... trying to salvage the majority of your code and your logic, one workaround I can think of would be to create a char array called last_product for example and fgets from the file until it's end, so the last entry read into the buffer will be the last line of the file.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ [c++] how do i turn user input an array?
r/learnprogramming on Reddit: [C++] How do I turn user input an array?
November 14, 2020 -

Working on some problems for school and I cannot figure out I am supposed to do this.

The problem at hand:

Ask the user to input two series of 10 integers. They can be double or single digits.

Turn them in to arrays and check if any of the values match.

I've seen suggestions online about setting each input to a char but wouldn't that include the spaces?

The only way I've been able to do this is to set it up where the user inputs a number, hits enter, rinse and repeat.

That's real simple. But I can't figure out how to take random spaces and numbers and fit them nearly into arrays.

Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ [c] user input string arrays
r/learnprogramming on Reddit: [C] User input string arrays
March 3, 2015 -

I've been trying to figure this out for a while now. I'm trying to user input strings into an array. I started out in Java, and would do it this way.

System.out.print("how many names will you enter? "); 
int length = input.nextInt(); 
int counter = 0; 
String[] names = new String[length]; 
for (String i: names){ 
    names[counter] = input.next(); 
    counter++;
    if (counter == names.length){ 
        input.close(); 
        int counter1 = 0; 
        for (String i1: names){ 
            System.out.printf("the string in index %d is '%s'\n", counter1,i1); 
            counter1++; } } }

In C, I can do this, but only with numbers. I have tried with for loops and while loops. I have googled it, but it seems that the only way to do it is an advanced way/requires more C programming knowledge and I basically don't understand what is happening when I see the example code.

This is my latest attempt. I can enter one string then after I enter the second one, it says the string i entered 'is not a valid command'

char *states[20];
int num_states = 4;

for(int i = 0; i < num_states; i++) {
    scanf("%s", states[i]);
}

for(int i = 0; i < num_states; i++) {
    printf("state %d: %s\n", i, states[i]);
}

Any way to do it similar to the Java way? Or must I have a deeper understanding of the C language?

๐ŸŒ
Programiz
programiz.com โ€บ c-programming โ€บ c-strings
Strings in C (With Examples)
Here, we have used fgets() function to read a string from the user. ... The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input which is the size of the name string.
Top answer
1 of 1
2

You can use scanf() function in order to achieve this.

The declaration of scanf function is as follows:

int scanf(const char *format, ...)

This means that while using scanf() function, you can specify the format of input you are receiving. Similar to printf() function, scanf("%c",&character), for example can be used to get character input from user. scanf() function returns the number of successful reads.

Note: You can check whether scanf() function successfully read the intended data by stating for example:

if (scanf("%d",&intNum)==1){
    //all is ok, proceed
}
else{
    //EOF or conversion failure
}

Likewise, if you are scanning for multiple variables, you can use if(scanf("%d %d",&intNum1,&intNum2)==2). Instead of %c, you can use any of the following(and more) in order to read and store different types of input.

Some of those:

c : character
d : decimal integer
f : float
o : octal integer
s : string of characters
etc...

Furthermore; for example if you use scanf("%d %f",&integerNum,&floatNum);, you will be reading user's input in format int float(int SPACE float) and storing the values into integerNum and floatNum variables respectively. The SPACE character between "%d %f" is part of the format.

The second argument (&character in my case) is the address scanf() is going to store the value into. For more information about scanf() : scanf(). You can use scanf() inside a loop to store user input into your array.

Here is a working sample:

#include <stdio.h>

int main(){
    int array[20];
    int i;
    printf("Enter value to be stored in array> ");
    for (i=0;i<20;i++){
        //printf("Enter value to be stored in array[%d]> ",i);
        scanf("%d,",&(array[i]));
        //scanf("%d,",(array+i));
    }
    for (i=0;i<20;i++){
        if (i==19){
            printf("%d\n",array[i]);
            //printf("%d\n",*(array+i));
        }
        else{
            printf("%d, ",array[i]);
        }
    }
    return 0;
}

In this example I used scanf("%d,",&(array[i])); since the format of the user input is going to be like this: int,int,int,int,...(int COMMA int COMMA int COMMA ...).

Notice how array returns the address of the first element of the array. By using pointers, you could rewrite scanf("%d,",&(array[i])); as scanf("%d,",(array+i));.

You can use this code to store other kinds of data like float with minimal changes. For example, in order to use this to get float input from user;

  1. Replace int array[20] with float array[20]
  2. Replace scanf("%d,",&(array[i])); with scanf("%f,",&(array[i]));

Also do not forget to use the right formatting when printing the values in your array.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ c string input without using array brackets
r/learnprogramming on Reddit: C String input without using array brackets
May 9, 2024 -

Hi I have a task that currently seems impossible to me. I have to write a program which takes a string input from a user and determines its length. I am supposed to not use the library functions (such as strlen) to determine the length and I cant use the array index operator [].

I know about the relationship between arrays and pointers, but I have no clue how I can declare an array using only pointers. Once I declare the array I can iterate over it with a for loop without using brackets like this:

*(array + i)

The rest of the program is also no issue, its just that I don't know how to declare the array and let a user input a string without array brackets.

I read about some solutions on stackoverflow that use malloc or typedef, but unfortunately I am still a beginner that just started the pointer topic and don't know what these are. I am pretty sure that these are advanced topics and the task is supposed to be solvable without using them.

Thank you for your help!

๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ c-programming โ€บ 172935-user-input-array-size.html
User input array size!!
#include <stdio.h> int main(void) { int n; printf("Enter size of array\n"); scanf_s("%d", &n); float array[n]; for (int i = 0; i < n; i++) { scanf_s("%f", &array[n]); } printf("%f", array[n]); getchar(); getchar(); } ... You got correctly the data inside the array.
Top answer
1 of 2
3

Yes, but you need to make sure you have enough space to do so:

char input[3][50]; // enough space for 3 strings with
                   // a length of 50 (including \0)

fgets(&input[0], 50, stdin);
printf("Inputted string: %s\n", input[0]);

Using char **input does not have any space allocated for the input, therefore you cannot do it.

2 of 2
3

It's possible, but somewhat tedious, especially if you don't know the number of strings at the beginning.

char **input;

That much is fine. From there, you need allocate an array of (the right number of) pointers:

input = malloc(sizeof(char *) * MAX_LINES);

Then you need to allocate space for each line. Since you typically only want enough space for each string, you typically do something like this:

#define MAX_LINE_LEN 8192

static char buffer[MAX_LINE_LEN];
long current_line = 0;

while (fgets(buffer, sizeof(buffer), infile) && current_line < MAX_LINES)  {
    input[current_line] = malloc(strlen(buffer)+1);
    strcpy(buffer[current_line++], buffer);
}

If you don't know the number of lines up-front, you typically allocate a number of pointers to start with (about as above), but as you read each line, check whether you've exceeded the current allocation, and if you have realloc the array of pointers to get more space.

If you want to badly enough, you can do the same with each individual line. Above, I've simply set a maximum that's large enough you probably won't exceed it very often with most typical text files. If you need it larger, it's pretty easy to expand that. At the same time, any number you pick will be an arbitrary limit. If you want to, you can read a chunk into your buffer, and if the last character in the string is not a new-line, keep reading more into the same string (and, again, use realloc to expand the allocation as needed). This isn't terribly difficult to do, but covering all the corner cases correctly can/does get tedious.

Edit: I should add that there's a rather different way to get the same basic effect. Read the entire content of the file into a single big buffer, then (typically) use strtok to break the buffer into lines (replacing "\n" with "\0") to build an array of pointers into the buffer. This typically improves speed somewhat (one big read instead of many one-line reads) as well as allocation overhead because you use one big allocation instead of many small ones. Each allocation will typically have a header, and get rounded to something like a (multiple of some) power of two. The effect of this varies with the line length involved. If you have a few long lines, it probably won't matter much. If you have a lot of short lines, it can save a lot.

๐ŸŒ
Quora
quora.com โ€บ How-do-we-input-values-into-an-array-in-C-programming-Can-this-be-explained-with-an-example-programme
How do we input values into an array in C programming? Can this be explained with an example programme? - Quora
Answer (1 of 4): If you want to learn the way for input I hink you know array well, now moving on to topic, Lets learn how to access any array index first, array starts with index 0 and goes to index n-1, where n is the size of array, lets say array is of size 10 elements, so to fetch array ele...
Top answer
1 of 3
5

Some dialects of C have variable-length arrays (VLA), notably C99 (and GCC accepts them....)

But your teacher probably wants you to understand C dynamic memory allocation, and you should also test when scanf fails, so you might code:

int main(void) {
    int size, i;
    printf("Enter the size of the arrays:\n");
    if (scanf("%d", &size)<1) {
      perror("scan size");
      exit(EXIT_FAILURE);
    };

Actually, you'll better test against the case of size being negative! I leave that up to you.

    int *arr1 = calloc(size, sizeof(int));
    if (arr1==NULL) {
       perror("calloc arr1");
       exit(EXIT_FAILURE);
    }

You always need to handle failure of calloc or malloc

 printf("Enter the elements of the array:\n");
 for (i = 0; i < size; i++) {
    if(scanf("%d", &arr1[size])<1) {
      perror("scanf arr1[size]");
      exit(EXIT_FAILURE);
    }
 }

scanf_s is only existing in C11, and on a C11 compliant implementation you could use VLAs

I leave the rest up to you. You want to code a for loop to print every element of the array.

Of course you should call free appropriately (and I am leaving that to you). Otherwise, you have a memory leak. Some systems have valgrind to help hunting them. Don't forget to compile with all warnings & debug info (with GCC use gcc -Wall -g) then use the debugger (e.g. gdb).

Don't forget that a programming language is a specification (written in some document), not a software. You may want to glance into n1570. And you need to understand what undefined behavior means.

2 of 3
4

You can't use static memory allocation to allocate an array with a dynamic size. You'll need to dynamically request memory to be allocated to your program, by the operating system, of whatever dynamic size the use asks for.

Here's an example to get started:

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

void printArray(int *array, int size) {
    // Sample array: [1, 2, 3, 4, 5]
    printf("["); // [
    for (int i = 0; i < size - 1; i++) { // [1, 2, 3, 4, 
        printf("%i, ", array[i]);
    }
    if (size >= 1) printf("%i", array[size-1]); // [1, 2, 3, 4, 5
    printf("]\n"); // [1, 2, 3, 4, 5]
}

int main(void) {
    int count;
    printf("Enter the size of the array:\n");
    scanf("%d", &count);

    // ask for enough memory to fit `count` elements,
    // each having the size of an `int`
    int *array = malloc(count * sizeof(*array));
    if (!array) {
        printf("There was a problem with malloc.");
        exit(EXIT_FAILURE);
    }

    printf("Enter the elements of the array:\n");
    for (int i = 0; i < count; i++) scanf("%d", &array[i]);

    printArray(array, count);

    //do stuff

    free(array);
}
๐ŸŒ
Studytonight
studytonight.com โ€บ c โ€บ string-and-character-array.php
String and Character Arrays in C Language | Studytonight
Learn how to create a string, character arrays in C, string input and output and string functions in C.