0

My array is defined like this

int buffSize = 80;
char* buff = (char*) malloc(sizeof(char) * buffSize);

First, I thought &buff should be the same as &buff[0], but apparently, it isn't! Did I miss something here? This statement prints two different values for those two:

    printf("COMPARE: buff=%u, buff[0]=%u\n", &buff, &buff[0]);

Second, the reason I asked is because I'm trying to create a big buffer and "manually" divide it up to use with getline. Basically, I'd like to do something like this:

int byte_read, total_read = 0;
do
{
   read = getline(&buff[totalRead], buffSize, inFile); //where inFile is just a file handler
  totalRead += read;
}
while (byte_read > 0);
0x56794E
  • 20,883
  • 13
  • 42
  • 58
  • 1
    [Don't cast malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Sep 14 '15 at 02:23
  • You probably wanted `buffsize - total_read` in the `getline` call, otherwise you can overflow. – Weak to Enuma Elish Sep 14 '15 at 02:23
  • You seem to be mentally confusing a pointer with the thing it is pointing to. Don't do this; they are two completely separate entities. – M.M Sep 14 '15 at 02:33
  • "I'm trying to create a big buffer and manually divide it up to use with getline." - that doesn't make any sense. How is that different to just reading the whole file into a buffer? – M.M Sep 14 '15 at 02:37

1 Answers1

4

buff is a pointer, and &buff is the address of that pointer. On the other hand, &buff[0] is the address of the location the pointer points to, and should have the same value as buff.

In summary, expect buff and &buff[0] to have the same value.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • So because `getline` takes `&buff`, which is the address of the pointer to the char array, presumably, there's no clean way to do what I want as described above? – 0x56794E Sep 14 '15 at 02:27
  • @abcXYZ `getline` isn't taking `&buff`. I think you didn't understand my answer. – juanchopanza Sep 14 '15 at 02:31
  • This page said `getline` takes the address of the pointer, i.e., `&buff`: http://crasseux.com/books/ctutorial/getline.html I must've misunderstood something? – 0x56794E Sep 14 '15 at 02:33
  • @abcXYZ yes, it takes `&buff`, not `&buff[totalRead]`. This is because it may make the pointer point elsewhere (to a new memory allocation). It has no "append" functionality. – M.M Sep 14 '15 at 02:35
  • @M.M Right. It does take `&buff`, but is there anyway I can specify where it starts writing the value to in the buffer I pass? – 0x56794E Sep 14 '15 at 02:38
  • @abcXYZ No there is not. – M.M Sep 14 '15 at 02:38
  • @abcXYZ I see, you mean the `getline` function expects a pointer to a pointer, not that you pass `&buff` in your own code. Yes, that is correct. It expects a pointer to a pointer, so it can set the location that pointer points to. Sorry for the misunderstanding. – juanchopanza Sep 14 '15 at 02:43