2

I've started learning C yesterday, and the only other language I know is Python.

I'm having some trouble with arrays, because they are quite different from the Python lists.

I tried to print an array, not an element of it, but the array itself.

#include <stdio.h>

int array[3] = {1, 2, 3}

main(){
    printf("%i, %i", array[0], array);
}

What I got is 1 (obviously), and 4210692, which I can't understand from where it comes.

What I wanted to do first, is to make an array of arrays:

float a[1][4];
float b[4];

a[0] = b;
main(){
    printf("%f", a[0]);
}

but it returns a strange number, and not something like this is an array as Python does.

pr94
  • 1,263
  • 12
  • 24
Matteo Secco
  • 613
  • 4
  • 10
  • 19
  • 2
    I'd recommend to get a good textbook about C and get the basics right. First is to forget about Python when coding in C. – too honest for this site Apr 06 '17 at 20:34
  • 1
    As an aside, it should be `int main()`, not just `main()` – BusyProgrammer Apr 06 '17 at 20:40
  • 2
    printf won't print complex objects, only numbers and strings. For anything else you have to write a function that does all the steps for you (to get to the numbers and strings). If you want built-in behavior more close to python then maybe you should try C++ instead. – Per Johansson Apr 06 '17 at 20:41
  • The large number is a mangled form of the address where the array is stored. Arrays are second-class citizens in C. They exist, but they're very closely related to pointers. You can't do many operations on whole arrays in C without writing loops (about the only thing you can do is initialize a whole array, if you're careful). And you can't do assignments like `a[0] = b;` outside of functions in C. – Jonathan Leffler Apr 06 '17 at 21:00

3 Answers3

3

That is the memory address of the array (because of array-to-pointer decaying).

To correctly print pointers though, you should use %p.

Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
2

The "wierd" value you get from printing array is actually the memory address of the first element of the array.

In order to print an array, you need to use a for loop:

for (int i = 0; i < array_size; i++)
    printf("%d\n", array[i]);
BusyProgrammer
  • 2,783
  • 5
  • 18
  • 31
0

You can simply use for loop, like this :

#include <stdio.h>

int main(){
    int arr[10] = {12, 32, 34, 13, 42, 35, 14, 43, 16, 43}
    for(int i = 0; a <= 10; a++)
    {
        printf("%i ", arr[i]);
    }
}

output :

12 32 34 13 42 35 14 43 16 43

or you can make a Python-like array printer by making a function

void printarr(int *arr, int size){
    for (int i = 0; i <= size; i++)
    {
        if (i == 0)
        {
            printf("[%i, ", arr[i]);
        } else if (i == size)
        {
            printf("%i]", arr[i]);
        } else
        {
            printf("%i, ", arr[i]);
        }
    }
}

with that, you can print

[12, 32, 34, 13, 42, 35, 14, 43, 16, 43]