Jump to content

convertion error on C function

Blade_792

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
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 7 5800X | Asus B550-Creator ProArt | EK 240mm Basic AIO | 16GB G.Skill DDR4 3200MT/s CAS-14 | XFX Speedster SWFT 210 RX 6600 | Samsung 990 PRO 2TB / Samsung 960 PRO 512GB / 4× Crucial MX500 2TB (RAID-0) | Corsair RM750X | Mellanox ConnectX-3 10G NIC | Inateck USB 3.0 Card | Hyte Y60 Case | Dell U3415W Monitor | Keychron K4 Brown (white backlight)

 

Laptop (Narrative): Lenovo Flex 5 81X20005US | Ryzen 5 4500U | 16GB RAM (soldered) | Vega 6 Graphics | SKHynix P31 1TB NVMe SSD | Intel AX200 Wifi (all-around awesome machine)

 

Proxmox Server (Veda): Ryzen 7 3800XT | AsRock Rack X470D4U | Corsair H80i v2 | 64GB Micron DDR4 ECC 3200MT/s | 4x 10TB WD Whites / 4x 14TB Seagate Exos / 2× Samsung PM963a 960GB SSD | Seasonic Prime Fanless 500W | Intel X540-T2 10G NIC | LSI 9207-8i HBA | Fractal Design Node 804 Case (side panels swapped to show off drives) | VMs: TrueNAS Scale; Ubuntu Server (PiHole/PiVPN/NGINX?); Windows 10 Pro; Ubuntu Server (Apache/MySQL)


Media Center/Video Capture (Jesta Cannon): Ryzen 5 1600X | ASRock B450M Pro4 R2.0 | Noctua NH-L12S | 16GB Crucial DDR4 3200MT/s CAS-22 | EVGA GTX750Ti SC | UMIS NVMe SSD 256GB / Seagate 1.5TB HDD | Corsair CX450M | Viewcast Osprey 260e Video Capture | Mellanox ConnectX-2 10G NIC | LG UH12NS30 BD-ROM | Silverstone Sugo SG-11 Case | Sony XR65A80K

 

Camera: Sony ɑ7II w/ Meike Grip | Sony SEL24240 | Samyang 35mm ƒ/2.8 | Sony SEL50F18F | Sony SEL2870 (kit lens) | PNY Elite Perfomance 512GB SDXC card

 

Network:

Spoiler
                           ┌─────────────── Office/Rack ────────────────────────────────────────────────────────────────────────────┐
Google Fiber Webpass ────── UniFi Security Gateway ─── UniFi Switch 8-60W ─┬─ UniFi Switch Flex XG ═╦═ Veda (Proxmox Virtual Switch)
(500Mbps↑/500Mbps↓)                             UniFi CloudKey Gen2 (PoE) ─┴─ Veda (IPMI)           ╠═ Veda-NAS (HW Passthrough NIC)
╔═══════════════════════════════════════════════════════════════════════════════════════════════════╩═ Narrative (Asus USB 2.5G NIC)
║ ┌────── Closet ──────┐   ┌─────────────── Bedroom ──────────────────────────────────────────────────────┐
╚═ UniFi Switch Flex XG ═╤═ UniFi Switch Flex XG ═╦═ Byarlant
   (PoE)                 │                        ╠═ Narrative (Cable Matters USB-PD 2.5G Ethernet Dongle)
                         │                        ╚═ Jesta Cannon*
                         │ ┌─────────────── Media Center ──────────────────────────────────┐
Notes:                   └─ UniFi Switch 8 ─────────┬─ UniFi Access Point nanoHD (PoE)
═══ is Multi-Gigabit                                ├─ Sony Playstation 4 
─── is Gigabit                                      ├─ Pioneer VSX-S520
* = cable passed to Bedroom from Media Center       ├─ Sony XR65A80K (Google TV)
** = cable passed from Media Center to Bedroom      └─ Work Laptop** (Startech USB-PD Dock)

 

Retired/Other:

Spoiler

Laptop (Rozen-Zulu): Sony VAIO VPCF13WFX | Core i7-740QM | 8GB Patriot DDR3 | GT 425M | Samsung 850EVO 250GB SSD | Blu-ray Drive | Intel 7260 Wifi (lived a good life, retired with honor)

Testbed/Old Desktop (Kshatriya): Xeon X5470 @ 4.0GHz | ZALMAN CNPS9500 | Gigabyte EP45-UD3L | 8GB Nanya DDR2 400MHz | XFX HD6870 DD | OCZ Vertex 3 Max-IOPS 120GB | Corsair CX430M | HooToo USB 3.0 PCIe Card | Osprey 230 Video Capture | NZXT H230 Case

TrueNAS Server (La Vie en Rose): Xeon E3-1241v3 | Supermicro X10SLL-F | Corsair H60 | 32GB Micron DDR3L ECC 1600MHz | 1x Kingston 16GB SSD / Crucial MX500 500GB

Link to comment
Share on other sites

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 comment
Share on other sites

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 comment
Share on other sites

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 comment
Share on other sites

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 comment
Share on other sites

Link to post
Share on other sites

12 minutes ago, Nayr438 said:

char* buffer = (char*) malloc(sizeof(char));

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

ohh, 1 byte wont be enough

ಠ_ಠ

Link to comment
Share on other sites

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 comment
Share on other sites

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 comment
Share on other sites

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 comment
Share on other sites

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 comment
Share on other sites

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 comment
Share on other sites

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 comment
Share on other sites

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 comment
Share on other sites

Link to post
Share on other sites

3 minutes ago, Blade_792 said:

i forgot how to use cin and cout

You don’t use cin and cout in C.

Write in C.

Link to comment
Share on other sites

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 comment
Share on other sites

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 comment
Share on other sites

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 comment
Share on other sites

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

×