Search code examples
cbufferansi-c

Populating a buffer from the return of a method fails... ANSI C


The code I have is quite simple in one method I have this:

// This line has an Intellisense Error: Initialization with {...} expected for aggregate object
char str[] = GetBuffer(); // x 64 will give us 512 (sector sized buffer) ;

The GetBuffer metod is this:

char * GetBuffer(void)
{
int idx = 0;
int offset = 0;
char *buffer[512];

for(idx =0; idx < 64; idx ++)
{
            // This line has an Itellisense Error: "Expected Expression"
    buffer[offset + idx] = {"E","R","A","S","E","D"," ", " "};

    offset += 8;
}

return *buffer;
}

Any ideas what's wrong with this? All I am trying to do - is populate a buffer with 512 bytes which contain the following string repeated: "ERASED " This is ANSI C (not C++) and it has been so long since I coded in ANSI C - please help and be kind!

Using Visual Studio 2012

EDIT 1 Ok lots of things have been fixed thanks to you guys - but no full answer yet. The str buffer holds 528 characters and not 512 and contains a lot of ERASED as expected but ends with

ýýýý««««««««îþîþ

Any ideas with this? And Oh boy I have a great deal of pure C reading to do - I have forgotten way too much!


Solution

  • there is problem with your buffer creation. you'd malloc such that it's not reclaimed by the function invoke routine. Second, you can't do assignment like the line you encountered a Itellisense error. You can use this:

    #include "stdlib.h"
    
    char * GetBuffer(void)
    {
        int i = 0, idx = 0;
        const char * cstr_init = "ERASED  ";
        char *buffer = (char*)malloc(512);
    
        for (idx = 0; idx < 512; idx+=8) {
            for (i = 0; i < 8; i++) {
                buffer[idx+i] = cstr_init[i];
            }
        }
    
        return buffer;
    }