florian2840
florian2840

Reputation: 49

Passing a char buffer to function

I have some problems with a pointer. My idea was to pass a buffer to a function in order to store the return data in this buffer. But, I do not know if it will work.

void main()
{
    char *buf = malloc(sizeof(char) *buf);
    memset(buf, 0x00, BUF_SIZE);
    sendCommand(buf);
}

sendCommand(char *buf)
{
    write(fd, "some commands", strlen("some commands"));
    readResponse(buf);
}

readResponse(char *buf)
{
    read(fd, buf, nbytes);
}

I know there is no error handling up to now. And some variables are not well defined. It just depends on the passing buffer. Will I see the data that I get in readResponse() in my main function?

Upvotes: 1

Views: 915

Answers (3)

ameyCU
ameyCU

Reputation: 16607

As in readResponse() as you read nbytes into buffer pointed by buf ,so you will get that data in main .

Some improvements to be done -

1. void main() -> int main(void) or int main(int argc, char *argv[])

2. char *buf = malloc(sizeof(char) *buf); -> char *buf = malloc(BUF_SIZE); // sizeof(char)=1 or maybe something you desire (not sure though what you want ??)

Note - remember to free allocated memory.

Upvotes: 3

John Bollinger
John Bollinger

Reputation: 180058

You have a remarkable number of significant problems in the code you presented, considering how short it is. Other answers have addressed those, though, and your question is not actually about any of them:

Will I see the data I get in readResponse() in my main function?

Yes, provided that argument buf is a pointer to an array large enough to accommodate nbytes bytes, and that the read() call in fact successfully reads any bytes, those bytes will afterward be visible in main() via the pointer it passed to readResponse(). More generally, if you pass a pointer as a function argument, the called function may manipulate the pointed-to object, including by modifying those parts of it that are not const. That's how the read() function itself is able to store the bytes it reads into your buffer, after all.

Upvotes: 1

Jens
Jens

Reputation: 72619

This won't do what you think it does:

char *buf = malloc(sizeof(char) *buf);

Did you mean to multiply with BUF_SIZE?

Upvotes: 0

Related Questions