[A89] Re: A problem
[Prev][Next][Index][Thread]
[A89] Re: A problem
> ya, here is the code:
> void start_engine(int x, int y)
> {
> int (*testmap)[x]= NULL;
> testmap = calloc (y, sizeof (*testmap));
> ... More code here
> and then it is used like a normal array. It was in the faq, where i should
> of looked first.
Interesting. I just read this entry in the FAQ, but keep in mind that this
is a _GCC extension_ and not _ANSI C_.
> > So what was the problem? The char fn[]? (should be const char *fn)
>
> now, here is a question i have, why a pointer? it works now with myself
> passing the filename as char fn[]. and I can't have it be a const, as i
> might have to change it when it goes on.
"char fn[]" is, for most intents and purposes, equivalent to:
"char* const fn"
Sebastian was very close, but had the const in the wrong spot. A very quick
primer:
In C, a pointer can have up to _two_ constant parts
1.) The pointer itself -- that is, the memory address we're using -- is
always constant.
2.) The values AT the address -- ie, fn[x] for each x -- are constant.
These can be mixed and matched, so we have 4 distinct possibilities:
1.) Nothing is constant.
ex. "char* fn"
2.) The data is constant, but the pointer can be changed to point to another
set of constant data (rare).
ex. "const char* fn"
3.) The pointer is constant, but the data it points to can be changed (this
is like the array we're using here).
ex. "char* const fn" or "char fn[]"
4.) Both the pointer and the data it points to are constant.
ex. "const char* const fn" or "const char fn[]"
You'll see that if we use #3 (either "char* const fn" or "char fn[]"), you
can change the data in the array, but not fn, which holds the actual address
of the array.
The equivalence of arrays and pointers here is important. "array[x]" is the
same as "*(array+x)". Array notation is just easier to use than the pointer
notation.
The filename here is a string, and in C, a string is an array of characters.
Passing each and every character to a function we call via the stack would
be a huge waste, so we just send the address of the array.
So when we pass "char fn[]" to the function, we're actually passing in a
constant memory address. This is the same as "char* const fn", which also
passes in a constant memory address.
> >Because it's more general. Arrays are, in fact, passed as pointers (yes,
I
> >have learned). I don't know if it would still work if you passed a
string
> >from a char* variable. It might.
>
> I tried, and it gave me a memory violation, but it is nice to know that.
> Thanks for your help.
That sounds strange -- are you sure that the non-array code is including a
null byte at the end?
-Scott
Follow-Ups: