4

i was watching an exercise in my textbook that says: Create a C program that take from the keyboard an array with length "N".

The question is: In C language, how can i create an undefined length array?

Thank you all.

6
  • There are no such things. Length of arrays are static, once allocated cannot be change. For a feature like that, you have to use dynamic memory allocation Commented Nov 11, 2015 at 16:29
  • 2
    @Haris Of course there are: variable length arrays. Commented Nov 11, 2015 at 16:30
  • @this, he is speaking about undefined length array! Commented Nov 11, 2015 at 16:33
  • your exercise say that you have to create an array with N elements which is not undefined: first ask to input the length and then read one by one the values from stdin. Anyway I think that the exercise mean an array of generic length. Commented Nov 11, 2015 at 16:34
  • Type a program in C that take from the keyboard an array with length "N" and calculate the inferior number, the major number, and the arithmetic average of the array. How would you solve it? (Sorry I'm trying to translate from italian to english). Commented Nov 11, 2015 at 16:38

3 Answers 3

3

Do not create an array of undefined length.

After getting the needed length N, if C99 use a VLA (Variable Length Array)

int A[N];

... or allocate memory

int *A = malloc(sizeof *A * N);
...
// use A
...
free(A);

[Edit]

Good to add validation on N before proceeding. Example:

if (N <= 0 || N >= Some_Sane_Upper_Limit_Like_1000) return;
Sign up to request clarification or add additional context in comments.

9 Comments

When i set int A[N]; i receive an error: Use of undeclared identifier 'N'.
@Michelangelo Poli Either your compiler is not C99 compliant or your have not declared N. Suggest 2nd method. If that fails, post your code.
@Michelangelo Poli If there are code limitations, best to initially post them in the question than later on add them to the answers.
I am 100% with you regarding the check for N < 0, but I disagree about the checks for N == 0 and N >= Some_Sane_Upper_Limit_Like_1000. I've seen such limits transform into really nasty bugs when the limit, which seemed to be insanely large to the programmer who wrote it, was surpassed by a valid use case. Now, whether you need to check for N == 0 is entirely up to the requirements of the subsequent processing (it may be sensible, or it may be just another unrequired limitation of usecases), but I regard any arbitrary upper limits as bugs waiting to strike.
I'd regard a stack overflow as bug waiting to strike too, so an upper limit is a good idea. Of course the code should be written so that if the input exceeds the upper limit then the program handles this situation correctly.
|
2

for more information about VLA in c99 The New C:Why Variable Length Arrays?

#include <stdlib.h>


int main(){
    int n;


    printf("size of array: ");
    scanf("%d",&n);
    // limit, and erro verification omited
    int f[n],i;

    printf("\nREADING INPUT\n");    
    for(i=0;i<n;i++){
        printf("\tValue of f[%d]: ", i);
        scanf("%d",f+i);
    }

    /*
    calc_max(f,n);
    calc_min(f,n);
    calc_avg(f,n);
    */
    printf("\n\nPRINTING VALUES:\n");
    for(i=0;i<n;i++){
        printf("\tValue of f[%d]= %d \n", i,f[i]);
    }
    return 0;
}

Comments

0

It is not easy to satisfy 100% your needs, but you can give it a try:

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

char *addMe(void);

int main(void){
    char *test = addMe();
    free(test);
    return 0;
}

char *addMe(void){
    unsigned int maxLength = 15;
    unsigned int i =0;

    char *name;
    int c;

    name = malloc(1);
    if(name == NULL){
        exit(1);
    }

    printf("Enter your name:>  ");

    while ((c = getchar()) != '\n' && c != EOF) {
        name[i++] = (char) c;

        if (i > maxLength) {
            printf("Names longer than %d not allowed!\n",maxLength);
            name[maxLength] = '\0';
            break;
        }else if (i < maxLength){
            name = realloc(name, maxLength + 2);
        }
    }

    name[i] = '\0';
    printf("Your name is:>  %s\nThe length is:>  %zu\n",name ,strlen(name));

    return name;
}

Output:

Enter your name:>  l
Your name is:>  l
The length is:>  1

As you probably noticed I allocated memory only for one letter, and if you need more it will be allocated to satisfy your needs. You can also with this approach to have control of a maximum size:

Enter your name:>  Michael jacksonnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Names longer than 15 not allowed!
Your name is:>  Michael jackson
The length is:>  15

Like I said, give it a try.

13 Comments

Shouldn't }else if (i < sizeof(char) * 15){ be }else if(i < maxLength){ ?
@stek29 you are a funny guy :)) Why should be else if(i < maxLength)? Both are OK. (i < sizeof(char) * 15) is the same as (i < maxLength) in my Example. I had my reasons why I used (i < sizeof(char) * 15)
could you please explain me why you used it? I'm just trying to learn)
Note: sizeof(char) is by definition 1, so using it is generally redundant.
Also, this code seems to make no sense... Why realloic on every iteration of input loop, ans why to 30nwhen max length seems to be 15?
|

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.