| | |
Defining arrays of variable(user specified) length
Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved |
•
•
Join Date: Jun 2008
Posts: 53
Reputation:
Solved Threads: 0
In C,how to define an array which is of a length specified by the user?
I tried writing a code, but outputs were strange. Sometimes first two elements are correctly displayed, sometimes only first. Other seems some random values (extremely large sometimes). May be the problem is in initializing the pointer. First I didn't use the pointer p in readArray() function. I don't really know why I am using it now, or whether there should be a separate pointer when &A[0] is same as A.
here is the code
I searched and couldn't get a solution. I got some things for C++ like this but not for C. Is there anything like new in C? (new allocates memory in C++ and java, how its different from malloc?)
PS: This is my first post in this forum, though I went through posting instruction, tell me if I should keep something in mind. Also I have done coding in Java for like 1 year, so don't hesitate to include complex solution, but as I am beginner in C/C++. I read first five chapters of "the complete reference C++, fourth edition" by Herbert Schildt (i.e. I think I understand basics of arrays and pointers) if thats useful anywhere to answer this question.
Thanks and regards
I tried writing a code, but outputs were strange. Sometimes first two elements are correctly displayed, sometimes only first. Other seems some random values (extremely large sometimes). May be the problem is in initializing the pointer. First I didn't use the pointer p in readArray() function. I don't really know why I am using it now, or whether there should be a separate pointer when &A[0] is same as A.
here is the code
C Syntax (Toggle Plain Text)
#include <stdio.h> void printArray(int arr [], int size); int * readArray(int size); int main(){ int size; // size of array to be given by user printf("Enter the size of the array "); scanf("%d",&size); printArray(readArray(size),size); getchar(); return 0; } int * readArray(int size){ int A [size], i, *p; p=&A[0]; for (i=0;i<size;i++){ printf("\nEnter the element no. %d: ",i+1); scanf("%d",(p+i)); A[i]=*(p+i); } return &A[0]; } void printArray(int *arr, int size){ int i=0; for (i=0; i<size;i++){ printf("%d ", *(arr++)); } printf("\n"); getchar(); }
I searched and couldn't get a solution. I got some things for C++ like this but not for C. Is there anything like new in C? (new allocates memory in C++ and java, how its different from malloc?)
PS: This is my first post in this forum, though I went through posting instruction, tell me if I should keep something in mind. Also I have done coding in Java for like 1 year, so don't hesitate to include complex solution, but as I am beginner in C/C++. I read first five chapters of "the complete reference C++, fourth edition" by Herbert Schildt (i.e. I think I understand basics of arrays and pointers) if thats useful anywhere to answer this question.
Thanks and regards
> but as I am beginner in C/C++
Unfortunately, reading schildt books won't clarify the issue either.
Pick a language and stick to it. Despite their recent common ancestry, and superficial similarity, using both of them well requires a C++ hat AND a C hat. C/C++ is just brain-damage.
> new allocates memory in C++ and java, how its different from malloc?
new calls an appropriate constructor, and malloc just gives you a block of uninitialised memory.
So in your case, you would need
> scanf("%d",(p+i));
You don't need p, just do
Unfortunately, reading schildt books won't clarify the issue either.
Pick a language and stick to it. Despite their recent common ancestry, and superficial similarity, using both of them well requires a C++ hat AND a C hat. C/C++ is just brain-damage.
> new allocates memory in C++ and java, how its different from malloc?
new calls an appropriate constructor, and malloc just gives you a block of uninitialised memory.
So in your case, you would need
int *A = malloc ( size * sizeof *A ); > scanf("%d",(p+i));
You don't need p, just do
&A[i] •
•
Join Date: Jun 2008
Posts: 53
Reputation:
Solved Threads: 0
>
yups that took the input from user and displayed the output correctly, but if I am right no array was created. Just an integer pointer.
So we have a way to dynamically allocate user inputs at contiguous location but not exactly in an array. Do we ?
Also I want to know exactly why my previous program behaving strangely.
And about C hat and C++ hat, I'll Google and see what they are.
thanks
C Syntax (Toggle Plain Text)
int *A = malloc ( size * sizeof *A );
yups that took the input from user and displayed the output correctly, but if I am right no array was created. Just an integer pointer.
So we have a way to dynamically allocate user inputs at contiguous location but not exactly in an array. Do we ?
Also I want to know exactly why my previous program behaving strangely.
And about C hat and C++ hat, I'll Google and see what they are.
thanks
Last edited by grvs; Jun 14th, 2008 at 11:28 am.
>And about C hat and C++ hat, I'll Google and see what they are.
Don't waste your time doing that. What Salem was trying to convey was that people has the tendency to write C/C++ implying that it is, somehow just a programming language. When indeed C is not C++, neither C++ is C, contrary to the believe of many books and new learners. It is better to treat them as they are, two completely different programming languages with some similar syntax.
> new allocates memory in C++ and java, how its different from malloc?
Closely related to the topic. C do not have garbage collector, therefore, every time you call malloc to allocate some block of memory you must make sure that when that memory is not needed you release it by making a call to the function free().
Get to the habit of making sure that each call to malloc needs to be verified by checking that there was not problem reserving that block of memory.
e.g.
example
Not related to the topic, but some how not possible to dismiss are those call to scanf() to read an integer from user. I don't want to overwhelm you, but feeling a waste of time to learn something you are going to have to unlearn later; hence my intention to warn you now.
Don't use scanf() for reading from input. Verifying what the user enters is very hard, specially strings.
Some alternative example here.
Don't waste your time doing that. What Salem was trying to convey was that people has the tendency to write C/C++ implying that it is, somehow just a programming language. When indeed C is not C++, neither C++ is C, contrary to the believe of many books and new learners. It is better to treat them as they are, two completely different programming languages with some similar syntax.
> new allocates memory in C++ and java, how its different from malloc?
Closely related to the topic. C do not have garbage collector, therefore, every time you call malloc to allocate some block of memory you must make sure that when that memory is not needed you release it by making a call to the function free().
Get to the habit of making sure that each call to malloc needs to be verified by checking that there was not problem reserving that block of memory.
e.g.
example
Not related to the topic, but some how not possible to dismiss are those call to scanf() to read an integer from user. I don't want to overwhelm you, but feeling a waste of time to learn something you are going to have to unlearn later; hence my intention to warn you now.
Don't use scanf() for reading from input. Verifying what the user enters is very hard, specially strings.
Some alternative example here.
Last edited by Aia; Jun 14th, 2008 at 11:58 am.
More on the differences - http://david.tribble.com/text/cdiffs.htm
> Just an integer pointer.
A is the pointer.
What malloc returns is in effect the array, when you access it via A (or any other variable who's type is int*)
> Just an integer pointer.
A is the pointer.
What malloc returns is in effect the array, when you access it via A (or any other variable who's type is int*)
•
•
Join Date: Jun 2008
Posts: 53
Reputation:
Solved Threads: 0
•
•
•
•
More on the differences - http://david.tribble.com/text/cdiffs.htm
> Just an integer pointer.
A is the pointer.
What malloc returns is in effect the array, when you access it via A (or any other variable who's type is int*)
•
•
•
•
> new allocates memory in C++ and java, how its different from malloc?
Closely related to the topic. C do not have garbage collector, therefore, every time you call malloc to allocate some block of memory you must make sure that when that memory is not needed you release it by making a call to the function free().
Get to the habit of making sure that each call to malloc needs to be verified by checking that there was not problem reserving that block of memory.
e.g.
example
•
•
•
•
Not related to the topic, but some how not possible to dismiss are those call to scanf() to read an integer from user. I don't want to overwhelm you, but feeling a waste of time to learn something you are going to have to unlearn later; hence my intention to warn you now.
Don't use scanf() for reading from input. Verifying what the user enters is very hard, specially strings.
Some alternative example here.
Last edited by grvs; Jun 14th, 2008 at 1:34 pm.
![]() |
Other Threads in the C Forum
- Previous Thread: Calling C++ library functions in C code
- Next Thread: how to free pointers which are to be returned
| Thread Tools | Search this Thread |
* ansi append array arrays bash binarysearch calculate centimeter changingto char character convert copyanyfile copyimagefile copypdffile creafecopyofanytypeoffileinc createprocess() database dynamic execv fflush fgets file floatingpointvalidation fork forloop function getlogicaldrivestrin givemetehcodez grade gtkwinlinux histogram homework i/o ide inches include infiniteloop initialization input interest intmain() iso keyboard km license linked linkedlist linux list looping lowest matrix microsoft multi mysql oddnumber open opendocumentformat openwebfoundation overwrite pdf pointer pointers posix power program programming pyramidusingturboccodes radix read recursion recv recvblocked reversing scheduling segmentationfault send sequential single socket socketprogramming stack standard strchr string suggestions test testautomation testing threads turboc unix urboc user variable whythiscodecausesegmentationfault win32api windowsapi






