This question already has answers here:
Unable to modify pointer variable passed as argument to a function
(2 answers)
Closed 5 years ago.
#include <stdio.h>
#include <stdlib.h>
static void get_string(char *ac)
{
ac = (char *)malloc (1 * sizeof (char));
printf("Enter the string to count vowels and consonants in a string using pointers: ");
scanf("%s", ac);
}
main(int argc, char *argv[])
{
char *ac = NULL;
get_string(ac);
printf("The Entered string is:%s", ac);
for(;;);
}
Could not get the entered string from the stack of function. Returns null.Can anyone help me in debug?
Function arguments in C is passed by value. Any changes made to the parameters from inside the called function will not reflect to the actual argument supplied at function call.
In your case, you wanted to change ac itself (not the content of the memory location it points to), so, that would need a pointer-to-ac.
That said,
Please see this discussion on why not to cast the return value of malloc() and family in C..
sizeof(char) is guaranteed to be 1 in C, no need to use it as multiplier
a memory allocation of 1 byte can only hold an empty string, that's probably meaningless (and erroneous) in your code.
Related
This question already has answers here:
returning string from function without malloc
(8 answers)
Closed 6 months ago.
In the below snippet, printf( ) prints same string even though the char array has been memset to 0.
#include <stdio.h>
#include <string.h>
char ip_addr[20];
char *ip_print(char *in)
{
memset(ip_addr,0,20);
strcpy(ip_addr,in);
return ip_addr;
}
int main()
{
printf("Ip addresses %s - %s",ip_print("226.0.0.1"),ip_print("10.1.1.1"));
return 0;
}
output-
Ip addresses 226.0.0.1 - 226.0.0.1
Expected output-
Ip addresses 226.0.0.1 - 10.1.1.1
As #Pablo said above ip_print() updates a global variable and returns the (same) address twice. The order of evaluation of arguments, however, is unspecified so the result is undefined behavior (it may print either address twice).
This question already has answers here:
How can I correctly assign a new string value?
(4 answers)
Closed 1 year ago.
#include<stdio.h>
int main() {
char R_FPD[] = "+00393E33mm/go";
char R_FPH[] = "+00393E33mm/go";
char R_Vel[] = "+00393E33mm/go";
char R_Tot[] = "+00393E33mm/go";
char str_msg[] = "{"+"flow_rate_per_day"+":"+R_FPD+","+"flow_rate_per_hour"+":"+R_FPH+","+"velocity"+":"+R_Vel+","+"totalizer"+":"+R_Tot+"}";
printf("%s", str_msg);
return 0;
}
i want to make it like a json object but its not working
Arrays in C decay to pointers to their first elements and adding pointers is not defined in C standard.
The simplest way to concatenate string like this is using sprintf function. It works like printf but it prints into a C-string.
In your case the pattern could be following:
char str_msg[BIG_ENOUGH];
sprintf(str_msg, "{flow_rate_per_day:%s,flow_rate_per_hour:%s,velocity:%s,totalizer:%s}", R_FPD,R_FPH,R_Vel,R_Tot);
BIG_ENOUGH should be larger then the longest string that can be formed. 256 should be enough in your case.
Alternatively you can use asprintf function that will automatically allocated a buffer of the right size. Remember to use free when the buffer is no longer needed.
char *str_msg;
asprintf(&str_msg, "{flow_rate_per_day:%s,flow_rate_per_hour:%s,velocity:%s,totalizer:%s}", R_FPD,R_FPH,R_Vel,R_Tot);
... use str_msg
free(str_msg);
This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Miscalculation of array size inside a function
(3 answers)
Closed 6 years ago.
When I use the size of function in the main function it works correctly. However when i use it in the reverse function it only returns 8. Any ideas why or did i incorrectly use it.(This is the beginning of a assignment where I must reverse a string passed to the reverse function. I may only pass the string and nothing else and cannot use the string.h library. If there is another way to accomplish this please let me know. I was planning on using the sizeof function to get the size then looping through the array and use a temp variable to reverse it as I loop.)
#include <stdio.h>
char reverse(char *x);
int main(int argc, char* argv[])
{
char word[] = "Apple pies";
printf("%s\n", word);
reverse(word);
printf("%s\n", word);
printf("%s\n", reverse(word));
printf("%s\n", word);
return 0;
}
char reverse(char *x)
{
char crud;
int lc =0;
size_t length = 0;
char *tmp = x;
while (*tmp++)
++length;
while (length > lc)
{
crud = x[length];
x[length] = x[lc];
x[lc] =crud;
length--;
lc++;
}
}
In reverse, x is just a pointer (that is, a char*). But in main, x is an array (that is, a char[11]). That sizeof trick only works on arrays, not pointers. You'll have to pass the length to reverse as a parameter (or use strlen). This is covered in more detail in another question and its answers.
Since you say strlen is forbidden in your situation (as is passing in the length via a parameter), you'll have to implement strlen manually. It's trivial:
size_t length_of_str(const char *x) {
size_t length = 0;
while (*x++) ++length;
return length;
}
In the main method when you call the sizeof function, you are passing an array. But in the 'reverse' function, the argument is a character pointer. When you call sizeof on a pointer, there is no guaranteed result. Often you get 4 when you call sizeof on a char pointer. But again, there is no guarantee that sizeof will always return that value. You should not use sizeof for pointers.
This question already has answers here:
returning a local variable from function in C [duplicate]
(4 answers)
Closed 7 years ago.
I'm trying to make a function which will receive a char * from the user and will print it.
It turns my value to something weird when I'm printing it.
**//input method**
char* readContactName(){
char tmp[20];
do{
printf("What is your contact name?: (max %d chars) ", MAX_LENGH);
fflush(stdin);
scanf("%s", &tmp);
} while (!strcmp(tmp, ""));
return tmp;
}
void readContact (Contact* contact)
{
char* tmp;
tmp = readContactName();
updateContactName(contact, tmp);
}
**//when entering this function the string is correct**
void updateContactName(Contact* contact, char str[MAX_LENGH])
{
printf("contact name is %s\n",&str); --> prints rubish
}
What did I miss here?
In your code, char tmp[20]; is local to the function readContactName(). Once the function finishes execution, there is no existence of tmp. So, the address-of-tmp also becomes invalid.
So, after returning, in the caller, if you try to use the returned pointer, (as you're doing in updateContactName(contact, tmp);()) it will invoke undefined behaviour.
FWIW, fflush(stdin); is also UB. fflush() is only defined for output streams.
Solution:
Define tmp as to be a pointer.
Allocate memory dynamically (using malloc() or family).
Once you're done using the allocated memory, you need to free() it also.
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
I am studying C programming and making some tests in Ubuntu with Geany. I have a question about pointers. When an array is declared in a function and then returned as a pointer, array values are lost in the main method. I could check this with a simple example:
#include <stdio.h>
char* msg ();
int main(int argc, char **argv)
{
char* p = msg();
int i;
for(i=0;i<=10;i++)
printf("i: %d, value: %c \n", i, p[i]);
return 0;
}
char* msg (){
char msg [] = "hello";
return msg;
}
The output is random values (excepting the first one that always is 'h'). I suppose that this is because the pointer passed out of the scope and the memory could be written by other functions.
But if the value of message is bigger enough (like thousands of characters for example or maybe less), values stand in the same memory place and I can read them despite of the array was created in other function.
What is the reason for this results?
Thank you so much.
Returning a pointer to an automatic local variable invokes undefined behavior.