0

while it hasn't been something which really stopped me from learning, there is something which has been keeping me awake for the last few days...

What is the difference between:

#define x 5

int i;              // primitive, range [−32767, +32767]
int ia[x];          // array of size[5]
                    // each containing one int, which has a range from [−32767, +32767]
int* ip = malloc(sizeof(int) * x);    // pointer to an array, with space for five integers, 
                                      // essentially the same except for that the allocated 
                                      // memory is on the heap 
                                      // (ie will remain allocated until it is manually freed)
struct five_int {   // manually defined and named datastructure, which is the same as the pointer above
    int one;        // memory has to be malloc'd and freed manually                
    int two;
    int three;
    int four;
    int five;
}               

// segmentation faults will arise with following values
i  = 32768;
ia = "0, 1, 2, 3, 4, 5" // or any of the integer values being higher than 32767
ip =        // same as above
five_int =  // same as above

// are following values the same (except for the byte size - yup intended)?
int in  = 1;
char cn = 1;

// is it possible to access a value (for example 7) in following
int is = 178;
long long lls = 178;
float fs = 17.8;
1
i  = 32768;

No reason at all why this wouldn't work. First, the size of int is 2^32 at the appliance, not 2^16. Second, even if you enter a higher value, it will never segfault. It will wrap around and go "back".

ia = "0, 1, 2, 3, 4, 5"

Not sure what you're trying to do there. First, you can't assign an array except upon initialization, that's valid for any array. Second, what you're trying to store there is not 5 integers, but a string literal of 16 characters.

Same goes for the array declared as a pointer and for the struct. You need to assign values individually.

// are following values the same (except for the byte size - yup intended)?
int in  = 1;
char cn = 1;

Yes, they are.

// is it possible to access a value (for example 7) in following
int is = 178;
long long lls = 178;
float fs = 17.8;

No. Not directly. You can with some maths operations.

| improve this answer | |
  • isn't this by default a signed integer, meaning the values can range from -2^16 to 2^16? But seeing how it will wrap around, does that mean that (2^16)+1 equals zero? – Vincent Oct 26 '15 at 11:38
  • As i said, the size of an int, at the appliance is 2^32. ints are, by default, signed, so the values are between: –2147483648 and 2147483647 So if: int n = 2147483647; n + 1 == –2147483648 – Irene Oct 28 '15 at 2:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .