Hi, i have a big doubt about passing an array of chars to a function.
What i need is to pass from main an array of chars to a function where a new array constant of chars is created and then copied to the original array to be returned back to main.
This is a "debug" code i've done from the original app i'm doing on linux Gcc.
I admit I'm a little weak on C these days
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void r(char *buf)
{
char buf1[1]; //This needs to be a constant lenght char array, not a malloc/calloc!
buf1[0]='O';
buf1[1]='\0';
memcpy(buf, buf1, 2);
//strcpy(buf, buf1);
//buf=buf1;
printf ("%s\n", buf);
printf ("%s\n", buf1);
}
int main(int argc, char *argv[])
{
char buf[1];
buf[0]='A';
buf[1]='\0';
r(buf);
printf ("res %s\n", buf);
}
It apears to me that you have declared an array of size 1 "char buf1[1]" and used two memory locations, one of which is outside the array, "buf1[1]='\0';"
try declaring "char buf[2]" to stop your segmentation fault.