954,480 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Sane way of dynamically allocating arrays beyond declaration.

Hello all. Essentially what I need to do is what is described in the topic, in the context of using winsock's recv() function.

I've made some code that does what recv() does to strings so that I could find a solution without dealing with the rest of the socket code. Like recv(), recb() takes as its arguments a buffer array to store a string of chars and the length of that array.

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
  
  char mystring[500]; // buffer with pseudo-unlimited capacity.
  char *realbuf; // actual buffer, trimmed of un-needed space
  
  int i;
  
  recb(mystring, 500);
  

  // trim & store 
  for (i=0; mystring[i] != '\0'; ++i){
        realbuf[i]=mystring[i];
  }
  realbuf[i]='\0'; // add null to avoid garbage characters
  
  printf("String: %s, Length: %d", realbuf, i); // print 
  	
  return 0;
}

int recb (char *buffer, int bufn) {
  int i;
  char *towrite="What's up earth."; // in recv() this'd be data received from client/server
  
  for (i=0; i <= bufn; i++) {
    buffer[i]=towrite[i];
  }
  
  return i-1; // recv() returns how many bytes it stored

}


Okay, so this might work fine. But it's kind of long and redundant. Is there a sane way of doing it?

gebbit
Newbie Poster
4 posts since Jun 2005
Reputation Points: 10
Solved Threads: 0
 

First, you can't write to realbuf because it doesn't point anywhere.

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You