Jump to content

Ok guys i have to make a function that can take entire phrases and can be also used on while cycle.

This is my function until now:

#include <stdio.h>

char getPhrase()
{
    char phrase[1024];
    scanf("%[^\n]c", phrase);
    phrase[sizeof(phrase)-1]=0;
    return phrase;
}

 

and when used on this main:

#include <stdio.h>
#include "GetPhrase.h"

int main()
{
    char str[1024];

    for(int i=0; i<3; i++)
    {
        str=*getPhrase();
        cout<<str;
    }

    return 0;
}

give me the error: "invalid conversion from 'char*' to 'char' [-fpermissive]" in the main line where i call the function.

Any suggestion?

Edited by Blade_792
i forgot the code block sorry
Link to comment
https://linustechtips.com/topic/1274755-convertion-error-on-c-function/
Share on other sites

Link to post
Share on other sites

@Blade_792 The function getPhrase() needs to return char *, not char. The line in main would be str = getPhrase();

 

Also, please use CODE boxes.

Main System (Byarlant): Ryzen 9 5950X | Asus B550-Creator ProArt | EK 240mm Basic AIO | 32GB G.Skill DDR4 3600MT/s CL16 | XFX Speedster SWFT 210 RX 6600 | Samsung 990 PRO 2TB / Samsung 990 EVO Plus 4TB | Corsair RM750X | StarTech 4× USB 3.0 Card | Realtek RTL8127 10G NIC | Hyte Y60 Case | Dell U3415W Monitor | Keychron K12 Blue (RGB backlight)

 

Laptop (Narrative): Lenovo Flex 5 81X20005US | Ryzen 5 4500U | 16GB DDR4 3200MT/s (soldered) | Vega II 384SP Graphics | SKHynix P31 1TB NVMe SSD | Intel AX200 Wifi | Asus 2.5G USB NIC | Asus ProArt PA278QV | Keychron K4 Brown (white backlight)

 

Proxmox Server (Veda): Ryzen 7 3800XT | ASRock Rack X470D4U | Corsair H80i v2 | 128GB Micron DDR4 ECC 3200MT/s | 2× Samsung PM963a 960GB SSD / 4× WD 10TB / 4× Seagate 14TB Exos / 4× Micron MX500 2TB / 8× WD 12TB (custom external SAS enclosure) | Seasonic Prime Fanless 500W | Intel X550-T2 10G NIC | LSI 9300-8i HBA | Adaptec 82885T SAS Expander | Fractal Design Node 804 Case

 

Proxmox Server (La Vie en Rose)GMKtec Mini PC | Ryzen 7 5700U | 32GB Lexar DDR4 (SODIMM) | Vega II 512SP Graphics | Lexar 1TB 610 Pro SSD | 2× Realtek 8125 2.5G NICs


Media Center/Video Capture (Jesta Cannon): Ryzen 5 1600X | ASRock B450M Pro4 R2.0 | Noctua NH-L12S | 16GB Crucial DDR4 3200MT/s | EVGA GTX750Ti SC | UMIS NVMe SSD 256GB / TEAMGROUP MS30 1TB | Corsair CX450M | Viewcast Osprey 260e Video Capture | TrendNet (AQC107) 10G NIC | LG WH14NS40 BD-ROM | Silverstone Sugo SG-11 Case | Sony XR65A80K

 

Workbench (Doven Wolf): Lenovo m715q | Ryzen Pro 3 2200GE | 16GB Crucial DDR4 3200MT/s (SODIMM) | Vega 8 Graphics | SKHynix (OEM) 256GB NVMe SSD | uni 2.5G USB NIC | HDMI add-in module

 

Network:

Spoiler
                       ┌─────────────── Office/Rack ───────────────────────────────────────────────┐
Google Fiber Webpass ── Cloud Gateway Max ══╦═ Pro XG 8 ══╦═ Flex 2.5-8 ══╦═ Doven Wolf
                      La Vie en Rose (DNS) ═╬═ Narrative  ╠═ Veda-NAS     ╠═ La Vie en Rose (vmbr)
                                Veda (DNS) ─┘             ╠═ Veda (vmbr)  ├─ Ptolemy (vmbr)
╔═════════════════════════════════════════════════════════╩═ Ptolemy-NAS  ├─ Veda (Mgmt)
║   ┌ Closet ┐      ┌───────── Bedroom ─────────┐                         └─ Veda (IPMI)
╚═══ Flex XG ══╦╤═══ Flex XG ══╤╦═ Byarlant
       (PoE)   ║│              │╠═ Narrative 
Kitchen Jack ══╣└─ Dual PoE ┐  │╚═ Jesta Cannon*
   (Testing)   ║┌─ Injector ┘  └── Work Laptop
     Bedroom ══╝│        ┌─────── Media Center ────────────────────────────┐
     Jack #2    └──────── Switch 8 ────────────┬─ nanoHD Access Point (PoE)
Notes:                                         ├─ Sony PlayStation 4 
─── is Gigabit / ═══ is Multi-Gigabit          ├─ Pioneer VSX-S520
* = cable passed from Bedroom to Media Center  └─ Sony XR65A80K (Google TV)
Link to post
Share on other sites

2 hours ago, AbydosOne said:

@Blade_792 The function getPhrase() needs to return char *, not char. The line in main would be str = getPhrase();

 

Also, please use CODE boxes.

That wouldn't be a valid fix. The function would return a pointer to a local array that ceases to exist as soon as the function returns.

 

A solution would be to pass a pointer to str to the function for it to use.

Link to post
Share on other sites

Bonus gotcha:

cout<<str;

Yeah, no. Won't work in C (and - technically - not even in C++ unless you pollute your namespace).

 

Seems like someone copied stuff from the web without spending a second on thinking first, to be honest.

Write in C.

Link to post
Share on other sites

5 hours ago, Dat Guy said:

Seems like someone copied stuff from the web without spending a second on thinking first, to be honest.

Googling is easy, understanding hard! 😁

Hand, n. A singular instrument worn at the end of the human arm and commonly thrust into somebody’s pocket.

Link to post
Share on other sites

On 11/28/2020 at 3:17 PM, Blade_792 said:

return phrase;

This will get destroyed when the function ends making the result invalid. You need to allocate memory to store it then create a pointer.

Your also trying to store a dead pointer to a array. You can copy to an array but not assign a new value.

 

#include <stdlib.h>
#include <stdio.h>

char* getPhrase()
{    
    char* buffer = (char*) malloc(sizeof(char) * 1024);
    scanf(" %1023[^\n]c", buffer);
    return buffer;
}


int main()
{
    for(int i=0; i<3; i++)
    {
        char* phrase = getPhrase();
        printf("%s \n", phrase);
        free(phrase);
    }
    
    return 0;
}

 

or

 

#include <stdlib.h>
#include <stdio.h>

void getPhrase(char* ptr)
{    
    scanf(" %1023[^\n]c", ptr);
    return;
}


int main()
{
    char phrase[1024];
    
    for(int i=0; i<3; i++)
    {
        getPhrase(phrase);
        printf("%s \n", phrase);
    }
    
    return 0;
}

 

Edited by Nayr438
Added WereCatf's suggestion
Link to post
Share on other sites

13 hours ago, Dat Guy said:

Bonus gotcha:


cout<<str;

Yeah, no. Won't work in C (and - technically - not even in C++ unless you pollute your namespace).

 

Seems like someone copied stuff from the web without spending a second on thinking first, to be honest.

Honestly though, remember how it was like when you were first just learning to code.  I'm willing to bet you could have read a line of code without knowing the ins and outs of it.  e.g. Searching "how do you write a line c", if you come across an answer like cout<<str; you might go for it without knowing better.

 

6 minutes ago, Nayr438 said:

You need to allocate memory to store it then create a pointer.

While it's true, I don't think it's necessarily good practice using malloc within functions.  I agree with @Unimportant the approach should pass the pointer in.

The dangers of using malloc in the way that was suggested is that it other than the return type there is little indication on whether memory was allocated (e.g. if it was defined in other files so you didn't immediately see the source).  For all you know, it could be using static.

 

Trying to learn, or part of an homework assignment?  I ask because if it's learning, I would suggest not using getPhrase as a function if all you intend to do is call scanf.  It's better suited to just calling scanf in the function you are using.

 

If it's homework (and thus can't change the requirement of the getPhrase function), then consider either using static or as @Unimportantsaid try malloc.

3735928559 - Beware of the dead beef

Link to post
Share on other sites

20 minutes ago, shadow_ray said:

ohh, 1 byte wont be enough

I edited, maybe that's better. I haven't touched C or most languages for that matter in quite a few years.

 

20 minutes ago, wanderingfool2 said:

The dangers of using malloc in the way that was suggested is that it other than the return type there is little indication on whether memory was allocated (e.g. if it was defined in other files so you didn't immediately see the source).  For all you know, it could be using static.

I never really worried about it as I always referenced the functions that I was calling, but I do see your point.

With that said, for such a small basic function I wouldn't personally use malloc. It was more in reference to the original code.  I did however add a second example.

Link to post
Share on other sites

3 hours ago, Nayr438 said:


#include <stdlib.h>
#include <stdio.h>

void getPhrase(char* ptr)
{    
    scanf(" %[^\n]c", ptr);
    return;
}


int main()
{
    char phrase[1024];
    
    for(int i=0; i<3; i++)
    {
        getPhrase(phrase);
        printf("%s \n", phrase);
    }
    
    return 0;
}

 

I would like to point out that you should always, ALWAYS make sure you don't overflow the buffer you're accepting user-input into. With the scanf here, it should be limited to the size of phrase minus one for the ending NULL-character.

scanf(" %1023[^\n]c", phrase);

This is an extremely good thing to learn all the way from the start.

Hand, n. A singular instrument worn at the end of the human arm and commonly thrust into somebody’s pocket.

Link to post
Share on other sites

16 hours ago, Dat Guy said:

Bonus gotcha:


cout<<str;

Yeah, no. Won't work in C (and - technically - not even in C++ unless you pollute your namespace).

 

Seems like someone copied stuff from the web without spending a second on thinking first, to be honest.

i tried to find more information as possible but i can find only useless stuff in my language even when i try go to english website

Link to post
Share on other sites

6 minutes ago, WereCatf said:

I would like to point out that you should always, ALWAYS make sure you don't overflow the buffer you're accepting user-input into. With the scanf here, it should be limited to the size of phrase minus one for the ending NULL-character.


scanf(" %1023[^\n]c", scanBuf);

This is an extremely good thing to learn all the way from the start.

i tried this way but even if it has solved the problem now it generate a new one:

"error: incopatible type assignement of 'char' to 'char [1024]'"

Link to post
Share on other sites

16 hours ago, Dat Guy said:

Bonus gotcha:


cout<<str;

Yeah, no. Won't work in C (and - technically - not even in C++ unless you pollute your namespace).

yeah i know i forgot how to use cin and cout due to some problem on my pc whit the <iostram> library and was in hurry to write due to the fact that was somthing like midnight

Link to post
Share on other sites

4 minutes ago, Blade_792 said:

i tried this way but even if it has solved the problem now it generate a new one:

"error: incopatible type assignement of 'char' to 'char [1024]'"

I have no idea what you're talking about. There is no assignment on the line you quoted.

Hand, n. A singular instrument worn at the end of the human arm and commonly thrust into somebody’s pocket.

Link to post
Share on other sites

13 hours ago, WereCatf said:

I have no idea what you're talking about. There is no assignment on the line you quoted.

i have kinda solved using 

strcpy(str,getPhrase());

 

when i run the code it makes me enter the string once and after that it terminates without even giving the first output

Link to post
Share on other sites

2 hours ago, Blade_792 said:

i have kinda solved using 



strcpy(str,getPhrase());

 

when i run the code it makes me enter the string once and after that it terminates without even giving the first output

I posted why and 2 working examples above, with the second one being more of what you should use.

When you call "getPhrase();",  "char phrase[1024];" will never get returned. Its destroyed as soon as you hit "return phrase;" you end up returning a reference to a deleted object. Your application crashes when you try to reference the dead object.

Link to post
Share on other sites

10 hours ago, Nayr438 said:

I posted why and 2 working examples above, with the second one being more of what you should use.

When you call "getPhrase();",  "char phrase[1024];" will never get returned. Its destroyed as soon as you hit "return phrase;" you end up returning a reference to a deleted object. Your application crashes when you try to reference the dead object.

how can i solve?

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×