2

I've researched and I clearly understand that arrays are not pointers
But I've learned some things that I think, might be possible to declare an array-like variable using pointer declaration. Things that I'm aware:

  • Declaring a pointer uses dereference operator : int *x;
  • When declaring a pointer, I know it only holds memory address...
  • Echoing a value from array using pointer would be:
  • When declaring a[3], it allocates 3 empty memory addresses on the stack.
    So, it was like saying *(a+0), *(a+1), *(a+3) is allocated on stack for use. Array <code>a</code> given a scope of 3 of type intOn this photo I've given the a a scope of 3

I want to do the same precedence of memory address allocation declaration using pointers

Can I do something like that using pointers?
Making a declaration of pointer point to pointers to fetch different addresses would be easy as **p

I'm expecting the possibility to create a pointer declaration that allocates memory from the current address and the addresses it follows so it would be array-like structure

Example: I know int a[3]; using pointer declaration wouldn't be just int *(a+3)
If what I ask is impossible please answer why.


This is a simple code of a normal array's declaration and call: Ideone Code

#include <stdio.h>
char block[3]={1,2,3};// This line will be removed
//And would create a pointer declaration of that having array-like structure

int main() {
    while(i < sizeof(block))
    printf("%d", block[i++]);
    //And that I still could call the contents of it even just using *(block+i)
return 0;
}

Output: 123

Community
  • 1
  • 1
Aesthetic
  • 763
  • 1
  • 14
  • 31
  • like malloc() (http://www.cplusplus.com/reference/cstdlib/malloc/) ? – Gibby Feb 27 '14 at 15:37
  • can i get more clear about question and you mean creating array with the help of pointer?. – LearningC Feb 27 '14 at 15:37
  • @Rohith Yes, I'm expecting the output declaration to be an array-like... – Aesthetic Feb 27 '14 at 15:50
  • What is the actual problem you are trying to solve? – Lundin Feb 27 '14 at 15:52
  • Declare a Pointer with a Scope on the Stack somewhat like an array – Aesthetic Feb 27 '14 at 15:53
  • 2
    malloc allocates memory on heap no so you want to create array using pointer but the storage is on stack? so the usual method of using malloc is not the answer. is this what you meant in question ? – LearningC Feb 27 '14 at 15:57
  • A major distinction (but certainly not the only one) between declaring a var as `int[12]` vs `*int` is that the former allocates space for the array (on the stack if automatic variable, in the object if instance variable), while the latter does not. – Hot Licks Feb 27 '14 at 16:04
  • 3
    check this links [alloca in c](http://stackoverflow.com/questions/15639912/runtime-memory-allocation-on-stack) [c++ implementation](http://stackoverflow.com/questions/6335023/c-how-to-allocate-memory-dynamically-on-stack) these may help you. – LearningC Feb 27 '14 at 16:04
  • I'm always tagging this question in `memory-allocation` but when I save it, It becomes `memory-management` – Aesthetic Feb 27 '14 at 23:23
  • That's because [tag:memory-allocation] is an alias of [tag:memory-management] (note how it redirects). – MBlanc Mar 01 '14 at 16:31

6 Answers6

7

alloca()

As others here have noted, it's similar to malloc() but allocates the space in the stack frame instead.

However, its use is discouraged, as noted in this question. If you overrun the stack you won't get a "nice" error message. Instead, you'll get all sorts of undefined behaviour. Note however that the GNU libc manual does list some advantages of alloca() (with their corresponding disadvantages, though).

VLA (Variable-length array)

Variable-length arrays were a feature of C99 that was later relegated to a conditional feature in C11. Availability of VLA depends a lot on the C dialect you're using, and if you are willing to allow extensions (e.g, GNU C). It's main advantage over alloca() is that it provides array-like semantics.

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

static char* strrev(char* str)
{
    size_t i, len = strlen(str);
    char buffer[len]; /* Creates VLA from len variable */
    for (i = 0; i < len; i++) {
        buffer[len-i-1] = str[i];
    }
    return strncpy(str, buffer, len);
}
int main(void)
{
    char text[] = "Hello world!";
    printf("%s\n", strrev(text));
}

Decaying pointers

Note however, that arrays decay to simple pointers when they are passed on to a function as parameters.

int func(int  array[128]);
int func(int *array);

No matter which prototype you choose, taking sizeof(buffer) will yield the same value as sizeof(char*) inside the function bodies.

Inaccuracies in the question

I feel there were some slight slips in the question. I'm addressing them because I believe they will help us both understand the problem better. Having a common vocabulary goes a long way towards communicating complex ideas.

"Declaring a pointer uses dereference operator : int *x;"

Even if it looks the same, that's not the dereference operator. It says it in the very same page you linked:

Note that the asterisk (*) used when declaring a pointer only means that it is a pointer (it is part of its type compound specifier), and should not be confused with the dereference operator seen a bit earlier, but which is also written with an asterisk (*). They are simply two different things represented with the same sign.

"When declaring a[3], it allocates 3 empty memory addresses on the stack."

Newly allocated memory is not empty (how would you define empty memory?). The contents are indeterminate unless an initialisation is specified for the object (see §6.2.4).

"On this photo I've given the a a scope of 3."

3 is the length, the size or the number of elements. of 'a[]'.

Refer to §6.2.1 for the definition of a scope:

For each different entity that an identifier designates, the identifier is visible (i.e., can be used) only within a region of program text called its scope.

"I want to do the same precedence of memory address allocation declaration using pointers"

If you speak of "precedence", the first thing that comes to mind is operator precedence, which determines the order in which operations take place. Did you mean you wanted pointers allocated on the stack?

I'm expecting the possibility to create a pointer declaration that allocates memory from the current address and the addresses it follows so it would be array-like structure.

If you have a pointer to a valid block of memory

char* block = malloc(150);

You can already access it like an array:

block[6] = block[32];
Community
  • 1
  • 1
MBlanc
  • 1,773
  • 15
  • 31
  • Good links and response but can't still use it... Can you do a demonstration at this simple code http://ideone.com/oS5Lqn – Aesthetic Mar 02 '14 at 09:15
  • Whats wrong with the code example for VLAs? What exactly do you want demonstrated? Cheers! – MBlanc Mar 02 '14 at 09:53
  • I don't say it's wrong, I can't just implement it, At this link http://ideone.com/oS5Lqn runs a simple code using array, can you translate that declaration using the solution you mentioned and output it? – Aesthetic Mar 02 '14 at 09:56
  • The problem is that it's not completely clear what you are asking for in the question. I think you may be misunderstanding something about array declarations. [This](http://ideone.com/conDWc) Ideone illustrates what I understand when you say "*Declaring a Pointer with a Scope on the Stack somewhat like an array*". It simply declares the array inside a function definition. – MBlanc Mar 02 '14 at 10:24
  • +1 for a detailed attempt to answer all possible interpretations. – nonsensickle Mar 07 '14 at 01:48
  • 1
    I would ask that you also elaborate the **decaying pointers** section to include also a mention about the 3 different ways of declaring an array `int array[10]`, `int* array = malloc(10 * sizeof(int))` and `int* array = alloca(10 * sizeof(int))` because using `sizeof(array)` on each of them in turn will have the same results as your **decaying pointer** section. Also, I think that this is probably going to be the part of the core of the answer. – nonsensickle Mar 07 '14 at 01:51
6

If I understand this question correctly you are looking for alloca This allocates an arbitrary sized buffer onto the stack (in the current stack frame) and returns you a pointer to it. As it is on the stack it of course becomes invalid when your function returns.

Vality
  • 6,577
  • 3
  • 27
  • 48
1

Your terms are confusing me.

Anyway, if what you want to ask is whether you can allocate memory dynamically in the stack frame (of the caller)?

The answer is yes, you can do it by using alloca(3). This function is like malloc(), but instead of allocating memory in the so-called heap, it allocates memory in the current stack frame.

Lee Duhem
  • 14,695
  • 3
  • 29
  • 47
1

As per my understanding of your question .Normally array's would be decayed(treated) as pointers when you try to access the members of it as you explained in the first link you specified.

if you trying to allocate memory in run time and pointer to act as like array

you can do something like for your code using malloc

//  3 memory location's of size `int(4)` being allocated in heap who's starting address is pointed by `p` (returned to `p` by malloc)

x = 3; 
int *p = malloc(x*sizeof(int)) // for 1 2 3
int i = 0;  
p[i++] = 1;  //*(p+ i++)
p[i++] = 2;  //*(p+ i++)
p[i++] = 3;  //*(p+ i++)
i = 0;

int main() {
    while(i++ < x)      
    printf("%d", p[i++]);  // printf("%d", *(p+i)); 
    return 0;
}

or you want memory in stack you use alloca(3) as specified by others.

KARTHIK BHAT
  • 1,410
  • 13
  • 23
0

I am not that clear about what your question is exactly but is this the solution:

#include <stdio.h>
char block[]={1,2,3};
char *p=block;
int main() {
    int i=0;
    while(i < sizeof(block))
    {
    printf("%d", *(p+i));
    i++;
    }
return 0;
}
Prashant Anuragi
  • 390
  • 4
  • 14
0

When declaring a[3], it allocates 3 empty memory addresses on the stack.

When declaring sometype a[3];, it allocates 3 contiguous _cells_ with undefined content (not "empty") with automatic storage (not necessarily, but often, on a stack).

I want to do the same precedence of memory address allocation

Whatever that means, here is a stab in the dark where all elements are contiguous again:

char *line = "hello\0world\0goodbye\0world";
char *argv[] = {line+0, line+6, line+12, line+20};
jørgensen
  • 10,149
  • 2
  • 20
  • 27
  • -1. Your answer is vague (though I do appreciate that the question is too) and you haven't explained your solution to the *precedence* part of the question in sufficient detail. He seems to be a novice and your answer is not suited for one. – nonsensickle Mar 07 '14 at 01:47