Click here to Skip to main content
15,894,825 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Is it possible to create an array whose length is decided by only user, but not programmer.


error: segmentation fault (core dumped)

Is there any other way?

What I have tried:

#include<stdio.h>
int main()
{
int x;
printf("Enter the length of the character array:");
scanf("%d",x);
int a[x];
return 0;
}
Posted
Updated 25-Apr-21 6:54am
Comments
Patrice T 25-Apr-21 10:07am    
Depend on what size you want.
Dave Kreskowiak 25-Apr-21 10:24am    
Of course, this happens all the time in many applications. You just have to make sure the value entered is a reasonable one before trying to use it to create an array.

You can't define an array's size using a variable. x is a variable, so a[x] isn't allowed. You have to use malloc to allocate the array's memory. Your code shouldn't even compile!

I write C++, which allocates memory differently. But I believe this is what you want:

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

int main()
{
   int x;
   printf("Enter the length of the character array:");
   scanf("%d",x);

   int* a = (int*) malloc(x * sizeof(int));
   return 0;
}
malloc allocates bytes, so you need to allocate enough of them to hold x ints. malloc returns a pointer to the memory that it allocated. That's a void*, so you have to cast it to the type you want (an int*). You can then use a just like an array: a[0]...a[x-1].
 
Share this answer
 
You could answer most of your question for yourself by learning the language. See C reference - cppreference.com[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900