Cannot return and assign char array to pointer in C - c

char *test = "hello";
test = change_test("world");
printf("%s",test);
char* change_test(char *n){
printf("change: %s",n);
return n;
}
im trying to pass a 'string' back to a char pointer using a function but get the following error:
assignment makes pointer from integer without a cast
what am i doing wrong?

A function used without forward declaration will be considered having signature int (...). You should either forward-declare it:
char* change_test(char*);
...
char* test = "hello";
// etc.
or just move the definition change_test before where you call it.

printf() prints the text to the console but does not change n. Use this code instead:
char *change_test(char *n) {
char *result = new char[256];
sprintf(result, "change: %s", n);
return result;
}
// Do not forget to call delete[] on the value returned from change_test
Also add the declaration of change_test() before calling it:
char *change_test(char *n);

You're converting an integer to a pointer somewhere. Your code is incomplete, but at a guess I'd say it's that you're not defining change_test() before you use it, so the C compiler guesses at its type (and assumes it returns an integer.) Declare change_test() before calling it, like so:
char *change_test(char *n);

thanks a bunch guys! didnt think i would have this problem solved by lunch. here is the final test class
/* standard libraries */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* change_test(char*);
int main(){
char *test = "hello";
test = change_test("world");
printf("%s",test);
return (EXIT_SUCCESS);
}
char* change_test(char *n){
return n;
}

Related

C - passing argument 1 of 'send_data' makes pointer from integer without a cast

Im writing uart code for a microcontroller. My code is working fine with passing string("..."), but giving problem when i try to passing the char('.'). Yes, it is i've declared "s" a pointer for string, but there is a chance of passing char value. Is there any possibilities to pass both string and char values in send_data?
#include <stdio.h>
void send_data( char *s)
{
while(*s!='\0')
{
send_dt1(*s);
s++;
}
}
void send_dt1( char in_c)
{
printf("%c",in_c);
}
int main(void)
{
send_data("sample_data"); //fine
send_data('Q'); //warning, no data displaying
return 0; /* terminate the program */
}
Thanks..
As send_data expects s to be a null-terminated string anyway, I would just recommend using a string:
send_data("Q");
Notes:
you should pass a const char* around as long as you don't modify the string at s
send_data('Q'); //warning, no data displaying
Don't pass character to it . It expects a char * .
You can do this -
send_data("Q");
Also you should declare a prototype for function void send_dt1( char in_c) as you make a call to it before it's definition in function void send_data( char *s) .
This will also generate warning.
You can't pass a char to a function that expects a char *.
If you really need to be able to pass both, you'll need another function to accept a char and put it in a string so that send_data can be called:
void send_char_data(char c)
{
char s[2];
s[0] = c;
s[1] = '\0';
send_data(s);
}
....
int main(void)
{
send_data("sample_data");
send_char_data('Q');
return 0;
}

How to store result of type char in pointer?

I want to store result of type char in pointer which I'm passing as argument of function. Like this:
#include<stdio.h>
void try(char *);
int main()
{
char *result;
try(result);
printf("%s",result);
return 0;
}
void try(char *result)
{
result="try this";
}
But I'm getting result : (null)
Could someone tell me what's wrong here?
Your syntax only sends the pointer to the function. This allows changing the data the pointer points to, but not the pointer itself.
You would need to have
void try(char **result)
and call it
try(&result);
to change the actual pointer.
Another way is to copy data into the memory pointed by the pointer, but then you need to know there is enough memory available. Depends on the actual use case how to do it properly. You might use
strcpy(result, "what you want");
but then you really have to know that the memory pointed by result can handle 14 chars (remember the NULL in the end). In your current code you don't allocate memory at all for result, so this will invoke undefined behaviour.
The reason you're seeing NULL is because your compiler decided to initialize non-assigned pointers to NULL. Another compiler might initialize them to random values.
Also about terminology, you're not storing type char into a pointer. You may have a pointer pointing to a char, or in this case to a C type string, which is an array of chars.
You are creating another variable result inside try function.
Try printing result inside try function. It will work then.
If you really want to print inside main then try this -
#include<stdio.h>
void try(char **);
int main()
{
char *result;
try(&result);
printf("%s",result);
return 0;
}
void try(char** result)
{
*result = "try this";
//printf("%s\n",result);
}
Or if you don't want to get into double pointers, then this will work:
#include<stdio.h>
char* try(char *);
int main()
{
char *result;
result = try(result);
printf("%s",result);
return 0;
}
char* try(char* result)
{
result = "try this";
return result;
}
Also another way (no dynamic memory):
#include<stdio.h>
void try(char *);
int main()
{
char result[100] = {0};
try(result);
printf("%s",result);
return 0;
}
void try(char *result)
{
strcpy(result,"try this");
}
Note: When you say you got null, that doesn't mean anything - actually you had undefined behaviour there - because result was not initialized. I guess you invoked UB even before trying to print result, namely when you passed it to try. Because copy would be made in that method of the pointer, which would try to read value of original pointer - reading uninitialized variables is undefined in C. Hence always initialize your variables in C.

C: Function that recieves a pointer to pointer so it can allocate an external one

How can I make the following work? The idea is for the function to allocate an external pointer so I can use this concept in another program, but I can't do that because gcc keeps telling me that the argument is from an incompatible pointer type... It should be simple, but I'm not seeing it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int allocMyPtr(char *textToCopy, char **returnPtr) {
char *ptr=NULL;
int size=strlen(textToCopy)+1;
int count;
ptr=malloc(sizeof(char)*(size));
if(NULL!=ptr) {
for(count=0;count<size;count++) {
ptr[count]=textToCopy[count];
}
*returnPtr = ptr;
return 1;
} else {
return 0;
}
}
int main(void) {
char text[]="Hello World\n";
char *string;
if(allocMyPtr(text,string)) {
strcpy(string,text);
printf(string);
} else {
printf("out of memory\n");
return EXIT_FAILURE;
}
free(string);
return EXIT_SUCCESS;
}
It's almost correct, but as your function wants a pointer to a pointer, you have to pass the address of the pointer to the function, using the address-of operator:
allocMyPtr(text, &string)
You are passing string using pass by value in allocMyPtr() you should use pass by adress so that pointer should match otherwise compiler keep tellin you about ,
incompatible type char * to char **
do this :
if(allocMyPtr(text,&string)) { }
use &string instead to fix your problem the type related to this input parameter is char ** and not char *
if(allocMyPtr(text,&string)) {
Just a remark concerning your source code:
The allocMyPtr() function already do a copy from text to string.
so why you make copy agian with strcpy. it's useless
strcpy(string,text); // this useless

How can I cast a void function pointer in C?

Consider:
#include <stdio.h>
int f() {
return 20;
}
int main() {
void (*blah)() = f;
printf("%d\n",*((int *)blah())()); // Error is here! I need help!
return 0;
}
I want to cast 'blah' back to (int *) so that I can use it as a function to return 20 in the printf statement, but it doesn't seem to work. How can I fix it?
This might fix it:
printf("%d\n", ((int (*)())blah)() );
Your code appears to be invoking the function pointed to by blah, and then attempting to cast its void return value to int *, which of course can't be done.
You need to cast the function pointer before invoking the function. It is probably clearer to do this in a separate statement, but you can do it within the printf call as you've requested:
printf("%d\n", ((int (*)())blah)() );
Instead of initializing a void pointer and recasting later on, initialize it as an int pointer right away (since you already know it's an int function):
int (*blah)() = &f; // I believe the ampersand is optional here
To use it in your code, you simply call it like so:
printf("%d\n", (*blah)());
typedef the int version:
typedef int (*foo)();
void (*blah)() = f;
foo qqq = (foo)(f);
printf("%d\n", qqq());

pointers in c (beginner)

I just started to look at C, coming from a java background. I'm having a difficult time wrapping my head around pointers. In theory I feel like I get it but as soon as I try to use them or follow a program that's using them I get lost pretty quickly. I was trying to follow a string concat exercise but it wasnt working so I stripped it down to some basic pointer practice. It complies with a warning conflicting types for strcat function and when I run it, crashes completly.
Thanks for any help
#include <stdio.h>
#include <stdlib.h>
/* strcat: concatenate t to end of s; s must be big enough */
void strcat(char *string, char *attach);
int main(){
char one[10]="test";
char two[10]="co";
char *s;
char *t;
s=one;
t=two;
strcat(s,t);
}
void strcat(char *s, char *t) {
printf("%s",*s);
}
Your printf() should look like this:
printf("%s",s);
The asterisk is unnecessary. The %s format argument means that the argument should be a char*, which is what s is. Prefixing s with * does an extra invalid indirection.
You get the warning about conflicting types because strchr is a standard library routine, which should have this signature:
char * strcat ( char * destination, const char * source );
Yours has a different return type. You should probably rename yours to mystrchr or something else to avoid the conflict with the standard library (you may get linker errors if you use the same name).
Change
printf("%s",*s);
to
printf("%s",s);
The reason for this is printf is expecting a replacement for %s to be a pointer. It will dereference it internally to get the value.
Since you declared s as a char pointer (char *s), the type of s in your function will be just that, a pointer to a char. So you can just pass that pointer directly into printf.
In C, when you dereference a pointer, you get the value pointed to by the pointer. In this case, you get the first character pointed to by s. The correct usage should be:
printf( "%s", s );
BTW, strcat is a standard function that returns a pointer to a character array. Why make your own?
Replacing *s with s won't append strings yet, here is fully working code :
Pay attention to function urstrcat
#include <stdio.h>
#include <stdlib.h>
/* urstrcat: concatenate t to end of s; s must be big enough */
void urstrcat(char *string, char *attach);
int main(){
char one[10]="test";
char two[10]="co";
char *s;
char *t;
s=one;
t=two;
urstrcat(s,t);
return 0;
}
void urstrcat(char *s, char *t) {
printf("%s%s",s,t);
}
pointers are variable which points to address of a variable.
#include "stdio.h"
void main(){
int a,*b;
a=10;
b=&a;
printf("%d",b);
}
in the follwing code you will see a int 'a' and a pointer 'b'.
here b is taken as pointer of an integer and declared by giving'' before it.'' declare that 'b' is an pointer.then you will see "b=&a".this means b is taking address of integer "a" which is keeping value 10 in that particular memory and printf is printing that value.

Resources