tags:

views:

101

answers:

4
    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?

+6  A: 

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.

KennyTM
A: 

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);
Jonathan Grynspan
+1  A: 

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);
dark_charlie
1. Let's hope n points to a string of less than 248 characters. 2. this is C not C++. There's no `new`, try `malloc()`/`calloc()` instead.
JeremyP
@JeremyP You are right, thanks for correcting me.
dark_charlie
A: 

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;
}
JB87