Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Doubt on passing an array of chars by ref

Status
Not open for further replies.

Microemission

Member level 3
Joined
Jan 4, 2005
Messages
59
Helped
4
Reputation
8
Reaction score
0
Trophy points
1,286
Activity points
619
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);
	
}
The result of the program on console is this:
Code:
O
O
res
Segmentation fault
of course the expected would be
Code:
O
O
res O
Appreciate some help plz
Tkx
 

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.
 
Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top