473,586 Members | 2,678 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can array[]=malloc()ed?

Friends,
cannot we malloc a array?
So, I tried the following code:

int main(void)
{
unsigned int y[3]={1,3,6},i,j;
for(i=0;i<3;i++ )
printf("before =%d\n",y[i]);
*y = 7; /* 1*/
for(j=0;j<3;j++ )
printf("after =%d\n",y[j]);
return 0;
}

In the above I derefered *y in the line indicated by1 (correct me if I
have used a wrong term since pointers are derefered in this way. But
in the above I have used array but derefered as a pointer since
an array always decays into pointers.) the array's first element value
changes. Considering this as a kind of proof that *y pointes to the
first element in a array I wanted to malloc the array y. I tried
various syntax but I only get warnings.
*y = malloc(sizeof y);
In spite of the warnings I have compiled the code and the code I not
have any run time error. Can somebody tell me the correct syntax?
By the malloc of above the array's first element's mem get
allocated, Am I correct?

What happens I we use a multi dimensional array?
Nov 13 '05 #1
14 8464
da***********@y ahoo.com wrote:
Friends,
cannot we malloc a array?
So, I tried the following code:

int main(void)
{
unsigned int y[3]={1,3,6},i,j;
for(i=0;i<3;i++ )
printf("before =%d\n",y[i]);
*y = 7; /* 1*/
for(j=0;j<3;j++ )
printf("after =%d\n",y[j]);
return 0;
}

In the above I derefered *y in the line indicated by1 (correct me if I
have used a wrong term since pointers are derefered in this way. But
in the above I have used array but derefered as a pointer since
an array always decays into pointers.) the array's first element value
changes. Considering this as a kind of proof that *y pointes to the
first element in a array I wanted to malloc the array y. I tried
various syntax but I only get warnings.
*y = malloc(sizeof y);
Since y is a pointer and *y is an integer, the compiler complained
that you were assigning a pointer from malloc() to an int.

Try this:
#define QUANTITY 4
int * x; /* one variable per line is preferred */
x = malloc(QUANTITY * sizeof(int));
/* or */
x = malloc(QUANTITY * sizeof(*x));

I'm not sure whether you are allowed to use y to point to something
else in your above code. I do know that it is not a safe practice
since the original array will be lost when you assign a new array
(dynamically allocated) to 'y'.

In spite of the warnings I have compiled the code and the code I not
have any run time error. Can somebody tell me the correct syntax?
By the malloc of above the array's first element's mem get
allocated, Am I correct? No. The malloc function returns a pointer to dynamically allocated
memory; not the memory itself.

What happens I we use a multi dimensional array?

You need more space.
Read the C FAQ below which explains how to allocate memory for
a multi-dimensional array.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Nov 13 '05 #2
da***********@y ahoo.com wrote:

Friends,
cannot we malloc a array?
So, I tried the following code:

int main(void)
{
unsigned int y[3]={1,3,6},i,j;
for(i=0;i<3;i++ )
printf("before =%d\n",y[i]);
*y = 7; /* 1*/
for(j=0;j<3;j++ )
printf("after =%d\n",y[j]);
return 0;
}

In the above I derefered *y in the line indicated by1 (correct me if I
have used a wrong term since pointers are derefered in this way. But
in the above I have used array but derefered as a pointer since
an array always decays into pointers.) the array's first element value
changes. Considering this as a kind of proof that *y pointes to the
first element in a array I wanted to malloc the array y. I tried
various syntax but I only get warnings.
*y = malloc(sizeof y);
If `y' is still declared as shown above, `*y' is an `int'.
malloc() does not return an `int' value; malloc() returns a
pointer. You cannot store a pointer value in an `int' variable.
In spite of the warnings I have compiled the code and the code I not
have any run time error.
After giving you the diagnostic, the compiler apparently
tried to help you by altering your code to a correct form,
perhaps something like `*y = (int)malloc(siz eof y)'. If this
is what happened, the result was to forcibly convert the pointer
returned by malloc() into a corresponding `int' value, and store
that converted value in `*y'. The conversion might or might not
make sense; it might not even produce a legitimate `int' value;
your program might perfectly well explode at this point -- or it
might appear to do something sensible. The code as it stands is
incorrect, and there's really no telling what it might do.
Can somebody tell me the correct syntax?
No, because you haven't explained what you are trying to
do. The compiler (apparently) chose a correction in an attempt
to get some sense out of your code, but I am just as ignorant
as the compiler about your true intention, and my "correction "
is no more likely to be the right one than the compiler's was.
Neither of us can read your mind.
By the malloc of above the array's first element's mem get
allocated, Am I correct?
I'm sorry: I cannot understand this question at all.
What happens I we use a multi dimensional array?


Everything depends on how you use it.

Your understanding of arrays and of memory allocation seems
to be incomplete. I recommend that you study Sections 6 and 7
in the comp.lang.c Frequently Asked Questions (FAQ) list

http://www.eskimo.com/~scs/C-faq/top.html

Sections 4 and 5 might also be helpful. Good luck!

--
Er*********@sun .com
Nov 13 '05 #3
Thomas Matthews wrote:
da***********@y ahoo.com wrote:
Friends,
cannot we malloc a array?
So, I tried the following code:

int main(void)
{
unsigned int y[3]={1,3,6},i,j;
for(i=0;i<3;i++ )
printf("before =%d\n",y[i]);
*y = 7; /* 1*/
for(j=0;j<3;j++ )
printf("after =%d\n",y[j]);
return 0;
}
In the above I derefered *y in the line indicated by1 (correct me if I
have used a wrong term since pointers are derefered in this way. But
in the above I have used array but derefered as a pointer since
an array always decays into pointers.) the array's first element value
changes. Considering this as a kind of proof that *y pointes to the
first element in a array I wanted to malloc the array y. I tried
various syntax but I only get warnings.
*y = malloc(sizeof y);
I'm not sure whether you are allowed to use y to point to something
else in your above code.


No, he cannot. An array is not a valid lvalue, meaning it can never
appear on the left hand side of an assignment operator. If you want to
resize an array you must be using heap memory from the start.

What he can do is something akin to this:

unsigned int *y, i, j;
y = malloc(3 * sizeof(int));
y[0] = 1; y[1] = 3; y[2] = 6;
for (i = 0; i < 3; i++) print y[i];
y = realloc(y, 4 * sizeof(int));
y[3] = 7; // *y = 7 actually assignes y[0] = 7.
for (j = 0; j < 4; j++) print y[j];

Pointer syntax and array syntax are interchangeable as long as what you
are working with is a pointer. If it is an array you can still access
with *arr but you cannot manipulate arr in any way.
What happens I we use a multi dimensional array?


Things get complicated.

NR

Nov 13 '05 #4
In 'comp.lang.c', da***********@y ahoo.com wrote:
cannot we malloc a array?


No. You can malloc a block of data and store its address into a pointer 'p'
of the same type, and act with 'p' like with an array, because '*(p + i)' is
the long form of 'p[i]'.

--
-ed- em**********@no os.fr [remove YOURBRA before answering me]
The C-language FAQ: http://www.eskimo.com/~scs/C-faq/top.html
<blank line>
FAQ de f.c.l.c : http://www.isty-info.uvsq.fr/~rumeau/fclc/
Nov 13 '05 #5
On 10 Oct 2003 09:09:01 -0700, in comp.lang.c ,
da***********@y ahoo.com wrote:
Friends,
cannot we malloc a array?
No. An array is a pre-allocated block of memory. You can't allocate it
with the *alloc functions.
unsigned int y[3];
*y = 7; /* 1*/
This sets the value of the first element to 1.
*y is the same as y[1]

In the above I derefered *y
Yes.
Considering this as a kind of proof that *y pointes to the
first element in a array
NO. Its a proof that *y IS the first element of the array !!
I wanted to malloc the array y.
You just can't do this. Forget the whole idea. An array is not
mallocable.
What happens I we use a multi dimensional array?


What happens when?

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #6
Mark McIntyre <ma**********@s pamcop.net> wrote:
On 10 Oct 2003 09:09:01 -0700, in comp.lang.c ,
da***********@ yahoo.com wrote:
Friends,
cannot we malloc a array?
No. An array is a pre-allocated block of memory. You can't allocate it
with the *alloc functions.
unsigned int y[3];
*y = 7; /* 1*/

^
This sets the value of the first element to 1. ^*y is the same as y[1]

^^ ^^^^

Err, is this Pascal programming by C-comment? ;-)

The above expression sets the value of the first element to 7;
*y is the same as y[0].

<SNIP>

Regards
--
Irrwahn
(ir*******@free net.de)
Nov 13 '05 #7
On 10 Oct 2003 09:09:01 -0700, da***********@y ahoo.com wrote:
Friends,
cannot we malloc a array?
So, I tried the following code:

int main(void)
{
unsigned int y[3]={1,3,6},i,j;
for(i=0;i<3;i++ )
printf("before =%d\n",y[i]);
*y = 7; /* 1*/
for(j=0;j<3;j+ +)
printf("after =%d\n",y[j]);
return 0;
}

In the above I derefered *y in the line indicated by1 (correct me if I
have used a wrong term since pointers are derefered in this way. But
in the above I have used array but derefered as a pointer since
an array always decays into pointers.) the array's first element value
changes. Considering this as a kind of proof that *y pointes to the
first element in a array I wanted to malloc the array y. I tried
y is an array. In most contexts, the expression y is converted to a
pointer to the first element of the array. In this context, y is
treated as if you had written &y[0]. Therefore *y is treated as
*&y[0] which is the same as y[0].

Note that *y does not point to anything. (You would not say y[0]
points to the first element.) *y is the first element of the array,
the same as y[0].
various syntax but I only get warnings.
*y = malloc(sizeof y);
Assuming a prototype is in scope, the compiler knows malloc returns a
pointer to void. We already established that *y is an unsigned int.
You cannot assign a pointer to an int without a cast.
In spite of the warnings I have compiled the code and the code I not
have any run time error. Can somebody tell me the correct syntax?
The absence of a run time error simply means that your particular
instance of undefined behavior is unfriendly. The correct syntax is
*y = (int)malloc(...

Why you would want to do this is another question. Once you have the
address in an unsigned int, what are you going to do with it. You
cannot dereference it since you can only dereference pointers and we
have already established the *y is not a pointer.
By the malloc of above the array's first element's mem get
allocated, Am I correct?
If you rewrite this in English, we can probably tell you it is
incorrect.

What happens I we use a multi dimensional array?


If you don't change anything, you will have even worse undefined
behavior, if there are grades of badness.
<<Remove the del for email>>
Nov 13 '05 #8
Eric Sosman <Er*********@su n.com> wrote in message news:<3F******* ********@sun.co m>...
da***********@y ahoo.com wrote:

Friends,
cannot we malloc a array?
So, I tried the following code:

int main(void)
{
unsigned int y[3]={1,3,6},i,j;
for(i=0;i<3;i++ )
printf("before =%d\n",y[i]);
*y = 7; /* 1*/
for(j=0;j<3;j++ )
printf("after =%d\n",y[j]);
return 0;
}

In the above I derefered *y in the line indicated by1 (correct me if I
have used a wrong term since pointers are derefered in this way. But
in the above I have used array but derefered as a pointer since
an array always decays into pointers.) the array's first element value
changes. Considering this as a kind of proof that *y pointes to the
first element in a array I wanted to malloc the array y. I tried
various syntax but I only get warnings.
*y = malloc(sizeof y);
If `y' is still declared as shown above, `*y' is an `int'.
malloc() does not return an `int' value; malloc() returns a
pointer. You cannot store a pointer value in an `int' variable.


You can't? What about the following:

int foo, *ptr;

ptr = &foo;
foo = (int)ptr;

In spite of the warnings I have compiled the code and the code I not
have any run time error.


After giving you the diagnostic, the compiler apparently
tried to help you by altering your code to a correct form,
perhaps something like `*y = (int)malloc(siz eof y)'. If this
is what happened, the result was to forcibly convert the pointer
returned by malloc() into a corresponding `int' value, and store
that converted value in `*y'. The conversion might or might not
make sense; it might not even produce a legitimate `int' value;
your program might perfectly well explode at this point -- or it
might appear to do something sensible. The code as it stands is
incorrect, and there's really no telling what it might do.
Can somebody tell me the correct syntax?


No, because you haven't explained what you are trying to
do. The compiler (apparently) chose a correction in an attempt
to get some sense out of your code, but I am just as ignorant
as the compiler about your true intention, and my "correction "
is no more likely to be the right one than the compiler's was.
Neither of us can read your mind.
By the malloc of above the array's first element's mem get
allocated, Am I correct?


I'm sorry: I cannot understand this question at all.
What happens I we use a multi dimensional array?


Everything depends on how you use it.

Your understanding of arrays and of memory allocation seems
to be incomplete. I recommend that you study Sections 6 and 7
in the comp.lang.c Frequently Asked Questions (FAQ) list

http://www.eskimo.com/~scs/C-faq/top.html

Sections 4 and 5 might also be helpful. Good luck!

- nethlek
Nov 13 '05 #9
My god,
Each element in the array is an int but not pointer to an int. If we
malloc the first element it will return a chunk of memory, which is a
pointer. Such a simple concept!
Some times my brain does not work correctly and gives UB!!

Can we allocate a array of pointer with malloc's by the following
method?
int main(void)
{
char *a = "dam",
*b="fool",
*c = "2003",
*d[3]={a,b,c};
unsigned int i;
for(i = 0;i<3 ;i++)
{
d[i] = NULL;
d[i] = malloc(sizeof **d);
if(**d == NULL)
{
printf("mem not allocated\n");
exit(EXIT_FAILU RE);
}
else
printf("mem allocated\n");
}
return 0;
}

Thanks for all the replays
Nov 13 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2855
by: Goh, Yong Kwang | last post by:
I'm trying to create a function that given a string, tokenize it and put into a dynamically-sized array of char* which is in turn also dynamically allocated based on the string token length. I call the function using this code fragement in my main function: --- char** arg_array; arg_count = create_arg_array(command, argument, arg_array); ...
19
3457
by: Hal Styli | last post by:
Hello, Can someone please help. I need to use a large array and I'm not sure when one should use (A) and when one should use (B) below:- #define MAX 10000000 (A) int x;
11
1931
by: Sushil | last post by:
Hi Gurus I've tried to come up with a small logical example of my problem. The problem is platform specific (MIPS) which I understand should not be discussed here. So here goes my example: Code is doing malloc of variable sizes. The last byte of malloc.ed memory is written a magic.
12
5498
by: arkobose | last post by:
my earlier post titled: "How to input strings of any lengths into arrays of type: char *array ?" seems to have created a confusion. therefore i paraphrase my problem below. consider the following program: #include<stdio.h> #define SIZE 1 int main()
5
2758
by: Bidule | last post by:
Hi, I'm trying to sort structs defined as follows: struct combinationRec { float score; char* name; }; The number of structs and the length of the "name" field are not known
0
1249
by: Gabriel de Dietrich | last post by:
Hi, I'm doing my first project on embedding and then extending Python in an application. The idea is to import a set of C++ plug-ins into Python and then be able to run a script that uses these plug-ins. Please note that what I'm importing into Python are the plug-in classes in order to be able to instanciate as many objects as needed. ...
7
3159
by: Sam | last post by:
Hello I have a structure called Company. struct Company { char *employee; char *employee_address; }; I want to build an array of this structure but the number of employees will change thorughout the course the programs use so it will need to
11
3941
by: seberino | last post by:
Suppose a C extension locally built an array of PyObject* 's as follows... my_array = malloc(n * sizeof(PyObject*)); for (i = 0; i < n; i++) { my_array = PyList_New(0); } Q1: Must I do a Py_DECREF(my_array) on all elements before exiting this C extension function? (What if
33
7150
by: Adam Chapman | last post by:
Hi, Im trying to migrate from programming in Matlab over to C. Im trying to make a simple function to multiply one matrix by the other. I've realised that C can't determine the size of a 2d array, so im inputting the dimensions of those myself. The problem is that the output array (C=A*B) has as many rows as A and as many columns as B. I...
0
7839
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8202
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7959
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8216
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6614
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5710
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3865
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1449
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.