Error Returning Address of Variable - c

We're supposed to write a function that will return the address of the first occurrence of ch in string str. I wrote the below code, which runs and seems to return numbers that could be correct (I called the function 5 times for the 5 characters in a string and the return values were separated by 1 byte.) However, the ampersand in the return statement is underlined in red with the hover-over text, "Return value type does not match the function type." I don't understand how the code builds and runs if there is an error.
#include <stdio.h>
#include <string.h>
int mystrchr (char *str, char ch){
int i;
for(i=0;i<strlen(str);i++){
if(str[i]==ch)
{
//printf("%c\n",str[i]);
return &str[i];
}
}
}

Let me tell you the reason:
From you defined funtion int mystrchr (char *str, char ch){}, the return type is int, but the real value is &str[i];, the type is char * in your code.
so there is a warning..

char* mystrchr (char *str, char ch){
int i;
for(i=0;i<strlen(str);i++){
if(str[i]==ch)
{
break;
}
}
return &str[i];
}
I agree with others.

Related

passing string to a pointer in c

I am fairly new in C. I want to assign string in a function to a pointer but I have no idea why it is not working?
This is the initial code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
void test(char* result) {
*result = "HELLO";
}
int main() {
char result[64];
test(result);
printf("%s", *result);
}
This is the error: warning: assignment makes integer from pointer without a cast. Since * result should store value and result is the address, shouldn't this work out?
Hello and welcome to C.
Your statement:
*result = "HELLO";
is the same as attempting to do the following:
result[0] = "HELLO"
which is attempting to set a single character to a string, and you can't do that.
you will need to copy the string character by character
luckily there is a function for that which you have included already with <string.h> called strcpy
strcpy(result,"HELLO")
This will work as long as your string to copy is fewer than 63 characters as you have defined in your main() function.
char result[64];
you should probably also send the length of the string to the test function and use strncpy
strncpy(result,"HELLO",length); // safe copy
and then terminate the string with '\0'
result[length-1] = 0;
your printf doesn't need to dereference the string pointer. So simply printf("%s",result); is fine.
so in summary:
void test(char* result,uint32_t len) {
strncpy(result,"HELLO",len); // safe copy (however "HELLO" will work for 64 length string fine)
result[len-1] = 0; // terminate the string
}
#define MY_STRING_LENGTH 64
int main() {
char result[MY_STRING_LENGTH ];
test(result,MY_STRING_LENGTH);
printf("%s",result); // remove *
}
You declared an array in main
char result[64];
Passed to the function it is converted to rvalue of the type char * that points to the first element of the array. The function deals with a copy of this pointer. Changing this copy of the pointer fors not influence on the original array.
Within the function the expression *result has the type char. So this assignment
*result = "HELLO";
does not make a sense.
In this call
printf("%s", *result);
there is again used an incorrect expression of the type char *result.
What you need is to use standard string function strcpy.
For example
#include <stdio.h>
#include <string.h>
void test(char* result) {
strcpy( result, "HELLO" );
}
int main( void ) {
char result[64];
test(result);
puts( result );
}
Problem:
When you store a character in a char varible,it puts the ASCII of the character in the memory.
char c='a';is the same aschar c=97;
You can verify this by using the code:
char c='a';
printf("%d",c);
So here is one way:
void test(char* result) {
*result++ = 'H';
*result++ = 'E';
*result++ = 'L';
*result++ = 'L';
*result = 'O';
}
int main() {
char result[64];
test(result);
printf("%s", result);
}
But it is redundant because there is a function called strcpy in <string.h>.
#include <stdio.h>
#include <string.h>
void test(char* result) {
strcpy( resul, "HELLO" );
}
int main() {
char result[64];
test(result);
puts( result );
}
Remove the '*' of the variable "result" after you've declared it and use the function "strcpy()" in your code.

retrieve letter from string in C

With the following C-function, I want to retrieve the letter at index idx from some string:
char get_letter(char *str, int idx)
{
return *(str + idx);
}
For example, the following:
char s[] = "Barack";
get_letter(s,2);
should return the letter 'r'.
Here is the whole program (name of the executable file is "retrieve"):
int printf(const char * restrict, ...);
char get_letter(char *, int);
int main(int carg, const char **varg){
if (carg != 2) return -1;
printf("%s", get_letter(varg[1],1));
return 0;
}
char get_letter(char *str, int idx)
{
return *(str + idx);
}
when I run the program (e.g.: ./retrieve test), instead of getting the letter "e", I get an error message ("Segmentation fault: 11").
What is going wrong here?
The possible print a character in C language as follows:
char c = 'j';
printf("%c",j);
Working code:
#include <stdio.h>
#include <stdlib.h>
char get_letter(char *str, int idx)
{
return *(str + idx);
}
int main()
{
char s[] = "Barack";
printf("%c", get_letter(s,2));
return 0;
}
I got it ... it has to be %c instead of %s in the print function.
You are returning a char* but your return type is char.
Change your return statement to return str[idx];
Also why you need a function for that? you can just write s[idx]. I am curious about the reason.

How to Return Char Array?

As you can see I have this code it takes a command (char array ) and divides it into two diffrent arrays if there is "|" between them.What I want is not to print it with the function but return these two new arrays to main and then print them ?
How can I do it ?
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
int a;
int status,n,i;
char command[4000];
write(STDOUT_FILENO,"Shell>",6);
n=read(STDIN_FILENO,command,4000);
void getArguments(char **,char*);
char *getStdOutFileName(char *);
if(n>0)
{
for(i=0;i<n;i++)
{
bugrafonk(command,&i);
printf("%s",First);
printf("%s",Second);
}
}
}
void bugrafonk(char* c,int*length)
{
int i;
int a;
char First[4000];
char Second[4000];
for(i=0;i<length;i++)
{
if(c[i]=='|')
{
i=a;
for(i=0;i<a;i++)
{
char First[i];
}
printf("---");
for(i=a;a<length;i++)
{
char Second[i];
}
}
}
return(First,Second); //is this true ?
}
There are some unnecssery declaration in the main now just avoid them I will use them later on.
To retun char * to main you need to send pointers to your function which are attached to memory that you can use
For example,
....
char return1[50]
char return2[50]
....
split_function(command, return1, return2);
....
The answer depends on where you store the results of your calculations.
In your current implementation both First and Second arrays are allocated inside the bugrafonk function and thus will be destroyed when the function is finished.
One possible option would be to allocate memory for result arrays outside the function and pass pointers to the function.
char first[4000], second[4000];
bugrafonk(..., first, second);
// use first and second
And bugrafonk implementation:
void bugrafonk(your arguments..., char *first, char *second)
{
...
}
Also, I have no idea what the mysterious word bugrafonk means ;)
The function implemented here splits the string by terminating the first part, and returns a pointer to the second part.
You don't need to return 2 pieces of information since you already know where the first string is. Note that this will not work if a string literal is passed since you cannot modify it, but that's not the case here.
#include <stdio.h>
#include <string.h>
char* bugrafonk(char* c); // function prototype
int main(void)
{
char command[4000];
char *split;
scanf("%3999s", command); // enter limited length string
split = bugrafonk(command); // this splits the string
printf("First part: %s\n", command); // print first half
if (split != NULL) // if there is a second half
printf("Second part: %s\n", split); // print second half
}
char* bugrafonk(char* c) // returns string pointer
{
char *cptr = strchr(c, '|'); // find that char
if (cptr != NULL) // if it was found
{
*cptr = '\0'; // terminate first part here
cptr++; // advance pointer to next part
}
return cptr;
}
Program output:
one|two
First part: one
Second part: two
You may choose to return a pointer to char, and then pass two arrays that will be modified in the body of the function.:
char *func(char arr[], char* arr2 /* other parameters */)
{ /* process arr and arr2 */
// return new array one. arr2 doesn't need to be returned.
return arr;
}
// in main:
char command[4000];
char arr2[4000]; // First
char *arr3 = func(command, arr2); // Second
Or just pass all arrays as arguments to the function and then return void, since they will be modified in the function.

How to pass array from library in c

I'm new in c programming and I want to pass array from library.
I have function in library c file that creates char array. How to use this array in main function. This is short code of something I tried:
libfile.c
char *myArray;
void PopulateArray()
{
// Getting data from serial port in char buffer[100]
myArray = buffer;
}
libfile.h
exter char *myArray;
void PopulateArray();
program.c
int main()
{
// in fore loop
printf("%s\n" , myArray[i]);
}
This is just one of combinations that I have tried but nothing works.
How to do this?
To pass an array from a library function to the surrounding code, you can use the return value of a function or use a pointer-to-pointer argument.
See the following example code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* createSourceCopy() {
const char *source = "Example Text";
// We got some text in variable source;
const size_t sourceSize = strlen(source);
char *result = (char*)malloc(sizeof(char)*(sourceSize+1));
strncpy(result, source, sourceSize);
return result;
}
A user of your library could use the function like this:
main() {
char *result = createSourceCopy();
// Do something with result.
// After the use, destroy the array
delete[] result;
return 0;
}
Another way how to pass an array is this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
bool copySourceText( char **outText ) {
const char *source = "Example Text";
// We get some text in variable source;
const size_t sourceSize = strlen(source);
*outText = new char[sourceSize];
strncpy(*outText, source, sourceSize);
return true; // success
}
This second variant has the benefit that the return value can be used as status. The function could return true on success, or false if there was an error.
This second version can be used like this.
int main() {
char *result;
if (copySourceText(&result)) {
// Do something with result.
// After the use, destroy the array
free(result);
result = NULL;
} else {
// Error handling
}
return 0;
}
It's not clear exactly what's going wrong in the code you posted (it would help to see more code), but assuming your problem isn't a compilation error, one of these lines might be wrong:
char *myArray;
printf("%s\n" , myArray[i]);
char *myArray declares a pointer to char (which would be appropriate for a single string).
The printf line dereferences myArray (producing a char, i.e. one character). You're passing down a char, but the %s format expects a pointer-to-char.
If you want to print the string character-by-character, you could use %c:
for (i = 0; i < length; i++) {
printf("%c\n", myArray[i]); /* or %x or %d if you want */
}
Otherwise, if myArray is one string and is null-terminated (see Why is a null terminator necessary?), then you could do:
printf("%s\n" , myArray); /* [i] removed, no for loop necessary */

Producing uppercase letters without pointers

I am trying to write a function, uppercase, that converts all lowercase characters in a string into their uppercase equivalents.
However, I am getting a Bus 10 error in my code. I know that string literals cannot be modified in C; so, I am not sure if this is the right approach.
My code is below:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
int uppercase(char source[])
{
int i;
for(i=0; i<=strlen(source); ++i)
if (source[i]>= 'a' && source[i]<= 'z')
source[i]= source[i]-'a' +'A';
else
source[i]=source[i];
}
int main(){
uppercase("cold");
return 0;
}
Ideally this function should return COLD.I suppose the error lies in my whole if statement.
The reason you get a crash is that your code modifies a string literal. Characters inside string literals are placed in protected memory area, and therefore may not be changed: it us undefined behavior.
Replace this
uppercase("cold");
with this:
char cold[] = "cold";
uppercase(cold);
Now the characters of the string are placed in a modifiable area of memory, allowing you to make changes as needed.
Your absolutly working with pointers without even to know it.
In your function definition
int uppercase(char source[])
char source[] is considered by the compiler as a pointer to char (char *source)
So when passing a string literal to uppercase() your just passing it's adress. Then in your function your trying to modify it which leads to undefined behaviour.
Also you can't return a whole array so you just return a pointer to it.
char *uppercase(char source[])
{
int i;
size_t len = strlen(source);
char *tmp;
tmp = malloc(len+1);
if (tmp!=NULL){
memcpy(tmp, source, len+1);
for(i=0; i<len; ++i){
if (tmp[i]>= 'a' && tmp[i]<= 'z'){
tmp[i]= tmp[i]-'a' +'A';
}
}
}
return tmp;
}
Then:
int main(){
char *str = uppercase("cold");
printf("%s", str);
free(str);
return 0;
}
You complete code: http://ideone.com/BJHDIF

Resources