Mechanic45
Mechanic45

Reputation: 173

How to declare a string so that it's length is given by the user in c?

So I've been asked to do that, and I did it like this:

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

    int main(void)
    {        
        int N,i;
        printf("Give the number of char's you want to input.\n");
        scanf("%d",&N);

        char *str = (char*) malloc(N);

        //this segment inputs the char's to the string.
        printf("Input the char's.\n"); 
        for (i=0;i<N;i++)
        {
           str[i] = getchar();
        }
        str[N] = '\0';
    }

Since I am a novince in c, I would like to know whether there is another/better way to do this. Thanks in advance.

Upvotes: 0

Views: 126

Answers (4)

chux
chux

Reputation: 153348

A better way is using fgets() and suggesting testing user input results.

printf("Give the number of char's you want to input.\n");

buf[40]; 
if (fgets(buf, sizeof(buf), stdin) == NULL) {
  Handle_EOForIOError();
}
int n;  // Suggest lower case 'n'
if (sscanf(buf, "%d", &n) != 1) Handle_SyntaxError();

char str[n+2];  // OP's VLA

if (fgets(str, sizeof(str), stdin) == NULL) {
  Handle_EOForIOError();
}

// Trim the \n if needed
size_t len = strlen(str);
if (len > 0 && str[len-1] == '\n') str[--len] = '\0'; 

Upvotes: 2

haccks
haccks

Reputation: 106012

Either use a variable length arrays ( allowed in C99 and latter ) or use dynamic memory allocation. Your approach is using VLA. You can also do this dynamically as:

int N;
printf("Give the number of char's you want to input.\n");
scanf("%d",&N);

char *str = malloc(N+1);  

Side notes:

  • Change main to its correct signature int main(void).
  • Array indexing starts with 0 in C. Initialize i to 0 instead of 1 and set the upper bound to i < N. Change your for loop to
for (int i = 0; i < N; i++)  
{
     str[i] = scanf(" %c");
} 
str[N] = '\0';
  • As suggested by H2CO3, do not use scanf, particularly with grtchar.
    Use fgets instead.

Upvotes: 2

user3159253
user3159253

Reputation: 17455

Well what you're trying to do is supported by C99 http://en.wikipedia.org/wiki/Variable-length_array . And GCC supports this from C90.

But actually this is The Bad Way to implement things. Such arrays are allocated on stack. This may be quite useful because their allocations and deallocations are damn fast, but this approach may lead to e.g. stack overflows.

Usually such tasks are implemented using dynamic allocations. See documentation for malloc http://linux.die.net/man/3/malloc and free http://linux.die.net/man/3/free More complete documentation with examples may be found here

Upvotes: 2

Lee Duhem
Lee Duhem

Reputation: 15121

I believe dynamic memory allocation using such as malloc() is a better solution to your problem, that means instead of

char str[N+1];

you should do

char *str = malloc(N+1);

And do not forget to free the memory by free(str); after you finished use it.

Upvotes: 3

Related Questions