0

I am asked to create a function with this prototype:

const char * members (char strings [] [TCAD], int rows);

char strings [] [TCAD] contains a series of records, which the function has to filter by extracting only the card number of each record. The definition of the function is as follows:

const char *members(char strings[][TCAD], int rows) {

int digits = 0;

char *ndigits = strings[1];

int ncommas = 0;

while (ncommas == 0) {

    if (ndigits[digits++] == ',') ncommas++;

}

char buffer[(digits+1)*rows];

for (int i = 1; i < rows; i++) {
    
    char *member = strings[i];

    char licence[digits+1];

    strncpy(licence, &member[0], digits);
    
    licence[digits] = '\0';
    
    strcat(buffer,licence);
}

printf("%s", buffer);

return buffer;

}

when I print the buffer within the same function I get my purpose.

ph20003,fc20015,cm19086,ve20008,mf19026,rc19106,ag19101,pg19065,lr19047,rf18025,aa19091,cc19089,hs20006,av19023,ft19004,dg17019,aa20047,rc19102,gr20035,rm19021,tq19002,ag17057,pc19060,hr18024,pm20072,tc20006,va17017,am18007,sm18038,cc20019,ff18023,vc17044,jm17015,ha19027,cd20017,mp19034,le19005,ma19074,cf20014,am19139,qj20001,pa19031,gs20027,ot20006,ze17002,ga19038,mh19029,fb19009,om20022,jg11008,gr12043,ar14078,vc20009,fa20011,mh19062,pr20028,ha17010,er20001,bc18029,

the problem is when I return the value of the buffer, I capture it in the main and try to print it in the main. The result is completely different and I print garbage. This is in the main function when I invoke the function:

const char *member = members(strings, rows);

printf("%s", member);

And nothing prints me. How can I return the value of the buffer and that I can capture that value in the main function?

  • 1
    [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) would be a good thing to read. If you need to return a pointer to memory that will exist after the function has exited you'll need to use `malloc` to allocate it and the caller must `free` it when it is finished with it. – Retired Ninja Sep 05 '21 at 03:10
  • Even if you properly allocate memory for `buffer` that persists after `members` returns, it's probably going to return garbage if `rows` is zero. And it's likely that starting with `i=1` is probably an off-by-one error unless you address `strings` with `i-1`. – Jeff Holt Sep 05 '21 at 03:16

0 Answers0