Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
#include<stdio.h>
#include<string.h>
main()
{
	char* newme(char* input1);
	char* newi;
	strcpy(newi,newme("platue..."));
	return 0;
}
char* newme(char* input1)

{
float p=22.9999,w=99.83234,r=333.523422;
	sprintf(input1," %.2f,%.2f,%.2f",p,w,r);
	printf("%s",input1);
	return input1;
}

The program is run on Dev C++ compiler and every time its run I get the message that the program has stopped working.

What I have tried:

i tried modifying the code, but the function must return a string, That's the only problem.
Posted
Updated 6-Sep-16 22:30pm

Quote:
strcpy(newi,newme("platue..."));
Before calling strcpy, newi must point to a valid allocated buffer (see strcpy - C++ Reference[^] for full details).


Quote:
sprintf(input1," %.2f,%.2f,%.2f",p,w,r);
Here you are trying to write over a read-only buffer (input1="platue...").


I suggest you reading a good tutorial on C pointers and strings.
 
Share this answer
 
There are a load of problems here.
You're passing a constant string to a function and then trying to write into it. That isn't allowed, any more than I can change your own name by writing mine over the top on your birth certificate!
It's because you declare a pointer to a character variable called newi but you don't give it a value at all. So when you try to copy the string that the function returns into it, it hasn't got anywhere to put it.

Try this:
C#
#include<stdio.h>
#include<string.h>

char* newme(char* input1);
int main()
{
    char data[100];
	char newi[100];
	strcpy(newi,newme(data));
	return 0;
}
char* newme(char* input1)
 
{
float p=22.9999,w=99.83234,r=333.523422;
	sprintf(input1," %.2f,%.2f,%.2f",p,w,r);
	printf("%s",input1);
	return input1;
}

It should work better.
 
Share this answer
 
You call function newme passing a pointer to a constant string ("platue..."). That function then tries to write into that string using sprintf and thus fails. You need to create a buffer large enough to hold the returned string and pass that, or allocate it inside the newme function and return its pointer to the caller. You also need to allocate a buffer to newi before your call to strcpy.
 
Share this answer
 
Here is links to references books on C and C++ by the authors of the languages. Note than C is the ancestor of C++, so knowing C is always useful with C++.
The C Programming Language - Wikipedia, the free encyclopedia[^]
https://hassanolity.files.wordpress.com/2013/11/the_c_programming_language_2.pdf[^]
http://www.ime.usp.br/~pf/Kernighan-Ritchie/C-Programming-Ebook.pdf[^]

C++ Programing Language[^]

Have a good lecture, looks you need it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900