user2683198
user2683198

Reputation: 35

How can I create an array in C without knowing the length beforehand? I can't assume the system will be using any specific standard

I tried doing something like:

int z = 1;
int *p = &z;
*(++p) = 2;
printf("%d",*p);

I would assume *p=22 and *(p-1)=1 but the code will compile and when I try to print it, it crashes. I will know the length at runtime, it's a user input.

Thank you.

Upvotes: 1

Views: 85

Answers (2)

user6409912
user6409912

Reputation:

z is a scalar.

int *p = &z; is valid. ++p is also valid as you are allowed to point one-past the address of a scalar.

But the behaviour on your dereferencing that pointer (with *(++p)) is undefined.

Consider using a variable length array (C99 onwards although even a C11 standard-compliant compiler can choose not to implement variable length arrays). Failing that, use malloc which has been part of the C standard since at least 1978.

Upvotes: 2

Alex Reynolds
Alex Reynolds

Reputation: 96937

You would use malloc and realloc to allocate and reallocate memory to pointers, to create arrays at runtime.

Note that de-referencing memory you haven't allocated -- i.e., space "outside" your runtime array -- is undefined behaviour that can cause crashes or other problems. Don't do it.

Upvotes: 1

Related Questions