Reference to a pointer is lost [duplicate] - c

This question already has answers here:
Assignment of function parameter has no effect outside the function
(2 answers)
Closed 9 years ago.
I am trying to understand why this statement doesn't work.
char resp[] = "123456789";
void getValue(char *im)
{
im = resp;
printf("\n%s\n",im);
}
int main(int argc, char *argv[])
{
char imei[11] = {0};
getValue(imei);
printf("\nIMEI: %s\n",imei);
return 0;
}
Output:
123456789
IMEI:

You can not assign with =, use strcpy instead:
#include <stdio.h>
#include <string.h>
char resp[] = "123456789";
void getValue(char *im)
{
im = strcpy(im, resp);
printf("\n%s\n",im);
}
int main(int argc, char *argv[])
{
char imei[11] = {0};
getValue(imei);
printf("\nIMEI: %s\n",imei);
return 0;
}
That's because imei is an array[11] (not just a pointer to), if you want to assign via = you can:
#include <stdio.h>
char resp[] = "123456789";
void getValue(char **im)
{
*im = resp;
printf("\n%s\n",*im);
}
int main(int argc, char *argv[])
{
char *imei; /* Not an array but a pointer */
getValue(&imei);
printf("\nIMEI: %s\n",imei);
return 0;
}

C passes parameters by value. Whatever change you ale to the im will be lost when the function exits. If you want to preserve the change. Pass the address of the pointer. Then you can change the pointer at the address you pass.

Try this:
char resp[] = "123456789";
void getValue(char **im)
{
*im = resp;
printf("\n%s\n",*im);
}
You need to pass a pointer to a pointer as your program argument.

Related

Julia retrieve global variable in C

I want to retrieve global variable x I just set in Julia from my C application.
Here's the code I have so far:
#include <julia.h>
void SimpleExecute(char *command, char *resultVar, char* result) {
jl_eval_string(command);
jl_value_t *var = jl_get_global(jl_base_module, jl_symbol(resultVar));
const char *str = jl_string_ptr(var);
sprintf(result, "%s", str);
}
int main(int argc, char *argv[])
{
char* result = malloc(sizeof(char) * 1024);
jl_init();
//(void)jl_eval_string("println(sqrt(2.0))"); //works
(void)SimpleExecute("x=sqrt(2.0)", "x", result);
jl_atexit_hook(0);
return 0;
}
However debugger shows that var is still NULL after jl_get_global call. Why?
I followed this tutorial but it does not touch on arbitrary variable retrieval. Source code shows similar usage.
I think there are a few things going on here:
First, you need to use jl_main_module and not jl_base_module.
Second, you cannot use jl_string_ptr to get the string value of a integer or floating point value. You can either use x=string(sqrt(2.0)) as the command to run, or use jl_unbox_float64 as a function to unbox the value you get back from Julia.
#include <julia.h>
#include <stdio.h>
void SimpleExecute(char *command, char *resultVar, const char* result) {
jl_eval_string(command);
jl_value_t *var = jl_get_global(jl_main_module, jl_symbol(resultVar));
if (var && jl_is_string(var)) {
const char * str = jl_string_ptr(var);
printf("%s\n", str);
} else {
const double val = jl_unbox_float64(var);
printf("%f\n", val);
}
}
int main(int argc, char *argv[])
{
char* result = malloc(sizeof(char) * 1024);
jl_init();
// (void)jl_eval_string("println(sqrt(2.0))"); //works
(void)SimpleExecute("x = sqrt(2.0)", "x", result);
jl_atexit_hook(0);
return 0;
}
You can run this by modifying the following:
cc -I/Users/$USER/Applications/Julia-1.3.app/Contents/Resources/julia/include/julia/ -Wl,-rpath,/Users/$USER/Applications/Julia-1.3.app/Contents/Resources/julia/lib/ -L/Users/$USER/Applications/Julia-1.3.app/Contents/Resources/julia/lib/ -ljulia main.c -o main

How to call a function with an array of strings

I've made a function, but I'm struggling with calling it.
This is the prototype of the function:
char *test(int argc, char **argv);
I've tried calling it this way but it doesn't work :
int main()
{
char tab[3][3] ={
"Yo",
"Hi"};
test(2, tab);
return (0);
}
For me this works:
char* test(int index, char** char2Darray)
{
return char2Darray[index];
}
int main()
{
char* tab[2] ={
"Yo",
"Hi"};
test(1, tab);
return (0);
}
I think there are two problems in your code :
the tab what you provided has only two item
your tab is a pointer which pointing to char[3] types and not char*
When you pass the 2D array
char tab[3][3]
to the function test(), it decays to a pointer of type:
char (*)[3]
which is a pointer to an array of 3 char elements.
This type is not compatible with char** which is a pointer-to-pointer to char. This is the source of your problem. You need to change the function test() to take char (*argv)[3] instead of char **argv.
Looking at function prototype:
char *test(int argc, char **argv);
char **argv is pointer of pointers and the variable char tab[3][3] is array of arrays so they are incompatible.
You can change function prototype to: char *test(int argc, char argv[][SOMECONSTANT]); or char *test(int argc, char (*argv)[3]);
This way
char * test(int argc,const char **argv);
int main()
{
const char * tab[3]=
{
"Yo",
"Hi",
0
};
test(2,tab);
return 0;
}
or
char * test(int argc,char **argv);
int main()
{
char arg1[]="Yo";
char arg2[]="Hi";
char * tab[3]=
{
arg1,
arg2,
0
};
test(2,tab);
return 0;
}

C - Pass Array of Strings as Function Parameter

I need to pass a pre-allocated array of strings as a function parameter, and strcpy() to each of the strings within the string array, as in this example:
static void string_copy(char * pointer[]) {
strcpy(pointer[0], "Hello ");
strcpy(pointer[1], "world");
}
int main(int argc, const char * argv[]) {
char my_array[10][100];
string_copy(my_array);
printf("%s%s\n", my_array[0], my_array[1]);
}
And the resulting printed string would be 'Hello world'.
How do I pass a pre-allocated string array and fill out each string within a function as shown above?
When you are doing string_copy(my_array), you are passing a char (*)[100], i.e. pointer to char[100] array to your function. But your function is expecting a char *[], i.e. array of char pointers, because you have defined your function that way.
You can fix this by making changes so that your function (string_copy()) expects a char (*)[100], instead of a char *[].
For this, you can change your function definition as:
/* Your my_array gets converted to pointer to char[100]
so, you need to change your function parameter
from `char *pointer[]` to `char (*pointer)[100]`
*/
/* static void string_copy(char *pointer []) */
static void string_copy(char (*pointer) [100])
{
strcpy(pointer[0], "Hello ");
strcpy(pointer[1], "world");
}
* Alternative Solution *
A different design/solution would be to change in your main() function so that you are actually passing a char *[], which decays into a char ** - which is fine - to string_copy(). This way you would NOT have to change your string_copy() function.
int main(int argc, const char * argv[]) {
char my_array[10][100];
int tot_char_arrs, i;
char *char_arr_ptr[10];
/* Get total number of char arrays in my_array */
tot_char_arrs = sizeof(my_array) / sizeof(my_array[0]);
// Store all char *
for (i = 0; i < tot_char_arrs; i++)
char_arr_ptr[i] = my_array[i];
/* Actually passing a char *[].
it will decay into char **, which is fine
*/
string_copy(char_arr_ptr);
printf("%s%s\n", my_array[0], my_array[1]);
}
you need to use a pointer to the array. here is an example with 1 dimension array:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
static void string_copy(char **pointer) {
strcpy(pointer[0], "Hello ");
}
int main(int argc, const char * argv[]) {
char my_array[10];
char * p_array = my_array;
string_copy(&p_array);
printf("%s\n", my_array);
}
Your function can simply accept matrix dimensions and pass a const char * that stores the array of literals (pre-allocated) strings:
#include <stdio.h>
#include <string.h>
#define STRINGS_LENGTH 100
static void string_copy(size_t n, size_t m, char pointer[n][m], const char *strings_to_copy[])
{
for (size_t i=0; i< n; i++)
{
strcpy(pointer[i], strings_to_copy[i]);
}
}
int main( void )
{
const char *strings[] = { "hello", "World" };
char my_array[sizeof(strings)/sizeof(strings[0])][STRINGS_LENGTH];
string_copy(sizeof(strings)/sizeof(strings[0]), STRINGS_LENGTH, my_array, strings);
printf("%s %s\n", my_array[0], my_array[1]);
}
You can also change the structure of your code using dynamic allocation for your output array like:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
static bool string_copy(char *pointer[], const char *strings_to_copy[], size_t strings)
{
for (size_t i=0; i< strings; i++)
{
pointer[i] = malloc(strlen(strings_to_copy[i])+1);
if (pointer[i] != NULL)
strcpy(pointer[i], strings_to_copy[i]);
else
return false;
}
return true;
}
int main(void)
{
const char *strings[] = { "hello", "World" };
char *my_array[sizeof(strings)/sizeof(strings[0])] = {0};
if (string_copy(my_array, strings, sizeof(strings)/sizeof(strings[0])) )
{
printf("%s %s\n", my_array[0], my_array[1]);
}
for (size_t i = 0; i<sizeof(strings)/sizeof(strings[0]); i++)
free (my_array[i]);
}

C pointer to string returning warning [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have the following code:
int ver(unsigned char** v) {
unsigned char str1[] = "1.0.2";
strcpy(v, str1);
return 0;
}
int main(int argc, char* argv[]) {
unsigned char s[10];
ver(s);
printf("version = %s", s);
return 0;
}
I get the following warning that the pointer differs in signedness. Can you please advise.
Change the declaration of ver to:
int ver(unsigned char * v)
I.e. get rid of one of the * characters.
Warning about signedness is because strcpy and printf("%s") expect a char*, but you are passing unsigned char*
Also int ver(unsigned char ** v) should be int ver(char* v)
Actually the problem is this :
int ver(unsigned char ** v)
You have to change the function to that :
int ver(unsigned char * v)
You need to do 2 fixes:
1) Follow what others told you about the method declaration, changing to "int ver(unsigned char* v) {" ;
2) Just include <string.h> at your code.
Example:
#include <stdio.h>
#include <string.h>
int ver(unsigned char* v) {
unsigned char str1[] = "1.0.2";
strcpy(v, str1);
return 0;
}
int main(int argc, char* argv[]) {
unsigned char s[10];
ver(s);
printf("version = %s", s);
return 0;
}
The cause of the warning:
strcpy() expects a signed char*, and is called with a unsigned char*.
But there should be other warnings as well:
Function ver() expects a pointer to a pointer:
int ver(unsigned char ** v){
ver(s) sends a single pointer to char:
unsigned char s[10];
ver(s);
To solve, you can change the code to:
int ver(char *v) {
char str1[] = "1.0.2";
strcpy(v, str1);
return 0;
}
int main(int argc, char *argv[]){
char s[10];
ver(s);
printf("version = %s", s);
return 0;
}

How do you pass a character array

I want to pass an array of characters i.e. a String in c
int main()
{
const char c[]="Joseph";
TestWord(&c,&c);
return 0;
}
int TestWord(char tiles[], char word[])
{
return tiles;
}
#include <stdio.h>
char *TestWord(char tiles[], char word[]);
int main()
{
char c[]="Joseph";
char r;
r = *TestWord(c,c);
return 0;
}
char *TestWord(char tiles[], char word[])
{
return tiles;
}
You pass through the arrays without the & as arrays don't need those, as they are already somewhat like pointers, just like how you would scanf an array without the & symbol.
Don't forget that if you are returning tiles that you should save that in a variable.
you could pass a string(character array) in C in many ways.
This code passes the string a to the function PRINT. Note that in this method the base address of the array is sent to the function.
#include<stdio.h>
void PRINT(char b[])
{
printf("%s",b);
}
int main()
{
char a[]="hello";
PRINT(a);
return 0;
}

Resources