简体   繁体   中英

Can I define and assign an integer array at the same time like we do with the string array?

Here is how I defined and assigned a string array at the same time

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

int main()
{
    string word = get_string("Enter a Word;");

    for(int i = 0; i<strlen(word); i++)
    {
        printf("%c\n",word[i]);
    }
}

Now I want to apply the same technique for taking integer values from user

#include <stdio.h>
#include <cs50.h>

int main()
{
    int scores[] = get_int("Enter score:");
    int len = sizeof(scores)/sizeof(int);

    for(int i = 0; i<len; i++)
    {
        printf("%i\n", scores[i]);
    }
}

But the code doesn't get compiled and compiler says like this:

IntArray.c:5:9: error: array initializer must be an initializer list or wide string literal
    int scores[] = get_int("Enter integer:");
        ^
1 error generated.
make: *** [<builtin>: IntArray] Error 1

I know we have a for loop for that solution, which goes like this: That's why I have to keep using for loop, which looks like this:

#include <stdio.h>
#include <cs50.h>

int main()
{
    int scores[3];

    for(int I = 0; I<3; I++)
    {
        score[I] = get_int("Enter score: ");
    }

    for(int j =0; j<3; j++)
    {
        printf("%I\n", scores[j]);
    }
}

My question is can I define and assign the integer array at the same time?

I tried to define and assign an integer array at the same time as we do with the single string, but I couldn't.

Can I define and assign an integer array at the same time like we do with the string array?

string word is not an array . That object is of a CS50 type string , which is a pointer, that points to an array of char .
Arrays are not pointers.
Pointers are not arrays.

Code can create similar code to define an int pointer...

// string word = get_string("Enter a Word;");
int *ints = get_ints("Enter ints;");

... and use a special value, like INT_MIN , to denote the end of the array of int s. Of course then INT_MIN is not available as a value to read. This is analogous to C strings , which uses a special value, the null character to signify the end of the array.


My question is can I define and assign the integer array at the same time?

Yes.

See @MM comment.

int scores[] = { get_int("Enter score:"), get_int("Enter score:"), get_int("Enter score:") };

This obliges that the array size is determined before getting the data.


Code could read the int s into some collection of data, then use the int count to define a variable length array (VLA). But VLAs may not be initialized. They could be assigned later.

some_tbd_data_collection_type data = 0;
unsigned n = get_ints(&data);
int a[n];
for (unsigned i = 0; i < n; i++) {
  a[i] = get_int(&data, i);
}
data_free(&data); 

Building on this earlier answer . The function read_ints reads integers until it reads end_of_list , after which it returns.

void read_ints(Array *a, int end_of_list)
{
    int current;
    while(1){
        scanf("%d",&current);
        if(current == end_of_list) return;
        insertArray(a,current);
    }
}
int main()
{
    Array a;
    initArray(&a, 5);
    printf("Enter numbers:");
    read_ints(&a,-1);

    for(int i=0; i<a.used; i++) printf("%d ", a.array[i]);
    return 0;
}

Here is how I defined and assigned a string array at the same time

This statement is incorrect. In the line

string word = get_string("Enter a Word;");

the variable word is not an array. In particular, the data type string is not an array, but rather a reference ("a pointer") to an array. You will learn this in week 4 of CS50 .

What really happens is that the function get_string creates an array based on user input and returns a reference to this newly created array. You then store this reference in the variable word . So you are creating a copy of the reference, not a copy of the array itself.

Here is an example program for demonstration purposes:

#include <cs50.h>
#include <stdio.h>

int main( void )
{
    string word1 = get_string( "Enter a word: " );
    string word2 = word1;
    word2[0] = 'J';

    printf( "\nContent of strings:\n" );
    printf( "word1: %s\n", word1 );
    printf( "word2: %s\n", word2 );
}

In the program above, if the user enters Test , then the line

string word2 = word1;

will not make a copy of the array containing the characters Test , but merely make a copy of the reference to the array. Afterwards, you will have two variables referencing the same array.

If you then modify the first character of the array using

word2[0] = 'J';

you will be modifying the array referenced by word1 and word2 . Therefore, the lines

printf( "word1: %s\n", word1 );
printf( "word2: %s\n", word2 );

will not output the original input Test , but will both output Jest .

For this reason, half of your question does not make sense, because initializing an array cannot be compared with initializing a reference ("a pointer") to an array.

My question is can I define and assign the integer array at the same time?

The line

int scores[] = get_int("Enter score:");

will not work.

On the other hand,

int scores[] = { get_int("Enter score:") };

will work, but this is probably not what you want, because it will only create an array of size 1 and calling the function get_int will only ask the user for a single int .

If you want to ask the user for several int values, then you will have to call the function get_int multiple times, for example like this:

int scores[] = {
    get_int( "Enter first score: "),
    get_int( "Enter second score: "),
    get_int( "Enter third score: ")
};

However, this solution is not ideal, especially if you later want to change your program to have more than 3 inputs. Therefore, not initializing the array in the declaration and using a loop instead (as you do in your last code snippet) would probably be the better solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM