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,025
  • 11
  • 23
Matteo Secco
  • 593
  • 2
  • 9
  • 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

2 Answers2

2

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
emlai
  • 39,703
  • 9
  • 98
  • 145
1

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,693
  • 5
  • 17
  • 31