opplo
|
  |
| Joined: 09 Dec 2008 |
| Total Posts: 5320 |
|
|
| 04 Dec 2016 07:00 PM |
I have a question for you about C. If you don't know C don't answer. I'm implementing a 2D array like so, by dynamically allocating a block of memory and computing offsets. I then give it to a function which fills in the array. When I try to print a certain value in the array it gives me the correct value, however when printing again straight afterwards it's giving me a different value from memory (even though it's looking in exactly the same area of memory).
void addData(int *array, size_t rows){ array[1 * rows * 1] = 21; array[1 * rows * 2] = 43; array[2 * rows * 1] = 5; array[2 * rows * 2] = 8; array[3 * rows * 1] = 5; array[3 * rows * 2] = 33; }
int main(int argc, char** argv) { size_t col = 2; size_t rows = 3; int *array = malloc(sizeof *array * col * rows); addData(array, rows); printf("%d\n", array[3 * rows * 2]); printf("%d\n", array[3 * rows * 2]); return (EXIT_SUCCESS); }
OUTPUT: 33 2
It should be giving me 33 both times but only prints it once. Any ideas why this is happening?
|
|
|
| Report Abuse |
|
|
| |
|
cntkillme
|
  |
| Joined: 07 Apr 2008 |
| Total Posts: 44956 |
|
|
| 04 Dec 2016 07:16 PM |
I just literally copy and pasted your code and it works perfectly fine for me Also why are you multiplying col and rows by sizeof(*array) instead of sizeof(int), even though in the normal case they will both be 4, if you compile for x64 you just allocate 2x more memory than you need to. |
|
|
| Report Abuse |
|
|
opplo
|
  |
| Joined: 09 Dec 2008 |
| Total Posts: 5320 |
|
| |
|
opplo
|
  |
| Joined: 09 Dec 2008 |
| Total Posts: 5320 |
|
|
| 04 Dec 2016 07:17 PM |
Hmm weird.
sizeof(*array) just points to the type of array which is an int anyway, makes it more flexible. |
|
|
| Report Abuse |
|
|
opplo
|
  |
| Joined: 09 Dec 2008 |
| Total Posts: 5320 |
|
|
| 04 Dec 2016 07:19 PM |
Works on online compilers just not NetBeans. This thread can end here, established the code isn't the issue. |
|
|
| Report Abuse |
|
|
cntkillme
|
  |
| Joined: 07 Apr 2008 |
| Total Posts: 44956 |
|
|
| 04 Dec 2016 08:15 PM |
"sizeof(*array) just points to the type of array which is an int anyway, makes it more flexible. " It makes it less flexible, did you not read what I just said? If you were creating an array of pointers then sure, but you're not. "if you compile for x64 you just allocate 2x more memory than you need to." |
|
|
| Report Abuse |
|
|