开发者

How to cycle through array without indexes in C?

I need to allocate an N sized array and assign it values, how can I do it without int indexes?

Here is the code I have so far but it doesn't do what I need:

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

int main() {
    int *array;
    int n;

    printf("Size of array: ");
    scanf("%d", &n);
    array = (int*) malloc(n*sizeof(int));
    if (array == NULL) printf("Memory Fail");

    for(; *array; array++)
    {
        printf("Store:\n");
        scanf("%d", &n);
        *array = n;
    }

    for(; *array; array++)
    {
        printf("Print: %d\n",*array);
    }

    free(array);
    return 0;
}
开发者_C百科

thanks


  1. for(; *array; array++); you should remove ; at the end
  2. Number of iterations for this loop is undefined and you are going to lose a pointer

You should do something like this:

int *cur;
for(cur = array; cur < array+n; ++cur)
{
    *cur = ...;
}


When you allocate the memory, you have no way to determine, in the memory, where it ends (unless you decide a convention and set a value somewhere, but anyway you would use n) .

In your case you have to use n to limit the array coverage (otherwise it is only limited by your computer capacity, and until it reaches an area where it does not have access: program crash). For instance (be careful not to overwrite n !)

  int v;
  int x = n;
  int *ptr = array;
  while (x--) 
  {
    printf("Store:\n");
    scanf("%d", &v);
    *ptr++ = v;
  }

  x = n;
  ptr = array;
  while (x--)
  {
    printf("Print: %d\n",*ptr++);
  }


You are using *array as your condition, which means the for loop should continue unless *array evaluates to false, which is only if *array == 0. You are actually invoking undefined behavior because you allocate array with malloc and are trying to dereference the pointer when the underlying data could be anything, since the data block has been uninitialized.

You still need some type of counter to loop with, in this case you allocated n items.

/* I'm using a C99 construct by declaring variables in the for initializer */
for (int i = 0; i < n; ++i)
{
    /* In your original code you re-assign your counter 'n', don't do that otherwise you lost the size of your array! */
    int temp; 
    printf("Store: \n");
    scanf("%d", &temp)
    array[i] = temp;
}

/* This is your second loop which prints the items */
for (int i = 0; i < n; ++i)
{
    printf("%d\n", array[i]);
}

Also, do not manipulate the array pointer without keeping a copy of it. You can only do free on the pointer returned by malloc.

Using indexes is the same as manipulating the pointer, your professor is being ridiculous otherwise.


If you have an array int *a; then:

a[0] is equal to *a
a[1] is equal to *(a+1)
a[2] is equal to *(a+2)

So you can go through the array by doing arithmetic on the pointer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜