473,398 Members | 2,125 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

int *a, indicator fault


I have the following code.

int *a;

for(int i=0;i<10;i++) {

a=i;

}

printf("%d", a[5]);



It occurs an error, What is wrong?

Could we have arrays with unknown length (when we define them)?
--
Posted via http://dbforums.com
Nov 13 '05 #1
3 1629
dominant <me*********@dbforums.com> wrote in
news:33****************@dbforums.com:

I have the following code.

int *a; for(int i=0;i<10;i++) { a=i; This would be a = &i; But this won't work because...
}

printf("%d", a[5]);
a[5] is at address of 'i' + 5 more int sizes further off in memory. You
don't own that memory.
It occurs an error, What is wrong?
Why not *point* 'a' at something appropriate!!!!???? You point to 'i'
which is a single int, not an array of 6 (yes 6) ints.
Could we have arrays with unknown length (when we define them)?


Look up malloc(), and don't cast its return value, just check for NULL
before using it.

--
- Mark ->
--
Nov 13 '05 #2
dominant wrote:
I have the following code.
What is wrong ? Let's see...

1) did you read the FAQ at http://www.eskimo.com/~scs/c-faq/top.html ?
If not, shame one you. Read it. It helps.
int *a;
a is a pointer to an int. Note that it does not point particularly anywhere.
for(int i=0;i<10;i++) {
Ah. You must have a C99 compliant compiler. In C89 (which is still the
most implemented version of the C standard), you could not declare i in
the for statement. No matter. i is an int, and will range from 0 to 9.
So far so good.
a=i;
Now this is a problem. a is a pointer. i is an int. You can't really
assign i to a and get meaningful, reliable and consistent results. Your
compiler should have produced a diagnostic on this line. If not, try to
pump up the warning level.
}

printf("%d", a[5]);
And now that's it. You are trying to access the 6th element of without
having ever prepared storage for it, *and* without even having assigned
a value to it (notwithstanding calling printf without a proper prototype
in scope... note that you should *always* post a compilable snippet of
code demonstrating you problem).
Could we have arrays with unknown length (when we define them)?

Yes we can. Let's tackle one problem at a time here. First of all, given
an array whose length you know, let's fill it out:

#include <stdio.h> /* for printf */
#include <stdlib.h>

int main(void)
{
int a[10]; /* a is an array of 10 ints */
size_t i; /* a size_t is more adapted than
an int for an array index. */

for (i = 0; i < 10; i++)
/* note that the following is also correct, a being an array
and avoids the issue of repeating the size of a:
for (i = 0; i < sizeof(a) / sizeof(*a); i++)
*/
{
a[i] = i * 2; /* a[0] = 0, a[1] = 2, a[2] = 4, ... */
}
printf("%d\n", a[5]); /* note that the \n is necessary to
*guarantee* that the printf will
actually output something *now* */

return EXIT_SUCCESS; /* portable values are EXIT_SUCCESS,
EXIT_FAILURE and 0 */
}

As you can see, there is a _big_ difference inside the for loop with
your code. Now, let's say you do not know the size of you array at
compile time. You need to use a pointer int *a, and you need to allocate
storage for the array it is going to point to, with malloc:

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

int main(void)
{
int *a;
size_t i;
size_t size_of_a;
int status = EXIT_SUCCESS;

size_of_a = 10;
a = malloc(size_of_a * sizeof *a); /* this means that we allocate
enough room for size_of_a times
the size of the type pointer to
by a (sizeof *a), in that case
int. */
if (NULL == a)
{
/* malloc can fail. If it does, you need to handle the failure
one way or another... */
puts("Could not allocate storage for a");
status = EXIT_FAILURE;
}
else
{
/* now a points to somewhere valid... */
for (i = 0; i < size_of_a; i++)
{
a[i] = 2 * i + 1;
}
printf("%d\n", a[5]);
}

return status;
}

Voila ! Now, you need to get a good C book (like Kernighan & Ritchie 2nd
edition), read the FAQ, and study some more...
--
Bertrand Mollinier Toublet
Currently looking for employment in the San Francisco Bay Area
http://www.bmt.dnsalias.org/employment

Nov 13 '05 #3
dominant <me*********@dbforums.com> writes:
I have the following code.

int *a;

for(int i=0;i<10;i++) {
a=i;
}
printf("%d", a[5]);
Please don't put a large number of empty lines between each non-empty
line in Usenet posts. (I have corrected this in the quotation.)
It occurs an error, What is wrong?
First of all, you are trying to assign an integer value (the value of `i')
to a pointer (`a'). This is not allowed in C; it's a constraint violation
and the compiler must emit a diagnostic.

Secondly, `a' is never initalized, i.e. it doesn't point to anything.
The expression `a[5]' therefore causes undefined behavior.
Could we have arrays with unknown length (when we define them)?


No, but you can use a pointer instead of an array for that. Before you
access the memory the pointer points to, you have to allocate said memory:
#include <stdlib.h>
#include <stdio.h>

int main (void)
{
int *a, i;

a = malloc (10 * sizeof *a);
if (a == 0)
{
fputs ("Cannot allocate memory.\n", stderr);
return EXIT_FAILURE;
}

for (i = 0; i < 10; ++i)
{
a [i] = i;
}

printf ("a [5] = %d\n", a [5]);

free (a);
return EXIT_SUCCESS;
}
Martin
Nov 13 '05 #4

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

Similar topics

10
by: Koen Janssens | last post by:
Can anybody give me an example on how to write a progress indicator in C++ using the standard library cerr or cout? My problem is I do not know how reset the output stream to the beginning of...
5
by: eskwayrd | last post by:
Hi group, I'm trying to add a busy indicator to the sorttable.js code available at: http://www.kryogenix.org/code/browser/sorttable/ (Actually, my version is modified for my needs, such as...
6
by: DebbieG | last post by:
I have created a database for a client and was told that it was to be a one-user database. Well, you know the next statement ... now they want 3 people to be able to use the database. (FYI, I...
7
by: Andrew | last post by:
Hello, Is it possible for a file position indicator of an input stream to be greater than the size of a file? And if so could this cause fgetc to somehow write to the file? For example is it...
1
by: Marko Vuksanovic | last post by:
I am trying to implement a file upload progress indicator (doesn't have to be a progress bar) using atlas... I do realize that the indicator cannot be implemented using Update panel control, but is...
6
by: Marko Vuksanovic | last post by:
I am trying to implement a file upload progress indicator (doesn't have to be a progress bar) using atlas... I do realize that the indicator cannot be implemented using Update panel control, but is...
14
by: Frank Swarbrick | last post by:
A few weeks ago I had posed a question about how one my create a cursor for a query where the predicate condition is dynamic. Meaning that the query might want to have one of several possible...
80
by: nicolas.sitbon | last post by:
Hi everybody, in a french C book, the author says that only {fgetc, getc, getchar, fgetwc, getwc, getwchar, fgets, gets, fgetws, getws, fputc, putc, putchar, fputwc, putwc, putwchar, fputs, puts,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
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,...
0
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...

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.