Why I cannot initialize an array with pointters? - c

I have tried to understand the connection between pointers and arrays. Why this prints "okkoD##"? Please help.
#include <stdio.h>
int main(){
char a = 'o';
char b = 'k';
char uga[2];
*(uga) = a;
*(uga+1) = b;
printf("%s", uga);
}

It is because a string in C is terminated by 0. So when you do this printf("%s", uga); the function will print the characters until it find the 0 element, then it stops. But there is none in uga, so it will keep printing characters from the stack. It is an undefined behavior. Try this
#include <stdio.h>
int main(){
char a = 'o';
char b = 'k';
char uga[3];
*(uga) = a;
*(uga+1) = b;
*(uga+2) = 0; // adding string terminating 0
printf("%s", uga);
}

Related

Concatenate two characters in c

How to concatenate two characters and store the result in a variable?
For example, I have 3 characters 'a', 'b' and 'c' and I need to join them together and store them in an array and later use this array as a string:
#include <stdio.h>
#include <string.h>
char n[10];
main ()
{
// now I want insert them in an array
//ex: n = { a + b + c }
}
There are many ways, the following 2 methods have exactly the same results: (using your code as a starting point.)
#include <stdio.h>
#include <string.h>
int main(void)
{
//Given the following
char a = 'a';
char b = 'b';
char c = 'c';
// assignment by initializer list at time of creation
char n1[10] = {a,b,c};
//usage of a string function
char n2[10] = {0}; //initialize array
sprintf(n2, "%c%c%c", a, b, c);
return 0;
}
Both result in a null terminated char arrays, or C strings.
Simply:
char a = 'a', b = 'b', c = 'c';
char str[4];
str[0] = a;
str[1] = b;
str[2] = c;
str[3] = '\0';
Or, if you want str to be stored on the heap (e.g. if you plan on returning it from a function):
char *str = malloc(4);
str[0] = a;
...
Any introductory book on C should cover this.
An assignment similar to that can only be done when the char array is declared using array initialiation with a brace-enclosed list:
char a = 'a', b = 'b', c = 'c';
char n[10] = {a, b, c};
After the declaration you can't do it like this because a char array is not a modifiable lvalue:
n = {a, b, c}; //error
To insert characters in an array that has been previously initialized, you need to either insert them one by one as exemplified in another answer, or use some library function like sprintf.
sprintf(n, "%c%c%c", a, b, c);
In both of my examples the char array will be null terminated by the compiler so you can use it as a string, if you assign the characters one by one, make sure to place a null terminator at the end ('\0'), only then will you have a propper string.

Why am I not getting the desired output?

The problem is to write the asked fibonacci word. For example if input is 0, then f(0) = a, if 1, f(1) = b and similarly f(2) = ba, f(3) = bab, f(4) = babba and so on. I wrote the following code to find the output on Ubuntu 18.04 LTS Terminal. I am getting the right output for n=0,1,2,3. But for n=4 I am getting babb instead of babba. I have tried debugging also but could not find where the code is going wrong. Kindly help me in finding the error.
#include <stdio.h>
#include <string.h>
void fibonacci(int n);
int main()
{
int x;
printf("Enter the fibonacci nword number you want to see:(f(x), f(0) is the starting element.):\n");
scanf("%d",&x);
printf("Required Word is:\n");
fibonacci(x);
return 0;
}
void fibonacci(int n)
{
int i,j=0;
char *p,*q,*r;
if(n==0)
{
printf("a\n");
}
else if(n==1)
{
printf("b\n");
}
else
{
char str1[100] = "a";
char str2[100] = "b";
char str3[100];
p = str1;
q = str2;
r = str3;
for(i=0;i<n-1;i++)
{
*r = *q;
strcat(str2,str1);
*p = *r;
}
printf("%s\n",str2);
}
}
First answering the main question, as of "Why I'm not getting the desired output":
Because you don't know what you're doing.
You are declaring 3 char[] variables statically, assigning them to pointers of type char*, and not even using them correctly.
Let's annalyze a part of your code:
for(i=0;i<n-1;i++)
{
*r = *q;
strcat(str2,str1);
*p = *r;
}
What you're doing is basically:
assign str3[0] = 'b' (in *r = *q)
copy the contents of str1 into str2, so, "ba" in the first run
assign str1[0] = 'b' (in *p = *r)
And then, repeatedly concatenate "b" into str2, because both str1 will only contain a single "b" for now on.
Doing that, for anything above 4, you'll only get "babbbbbbbbbb"...
My advice: If you're going to statically declare some variables, stop using pointers to access them. Try accessing the str1/str2 as vectors.
Your code is obfuscated. I modified it so:
#include <stdio.h>
#include <string.h>
char*fib(int n)
{
if (0==n)
return "a";
else if (1==n)
return "b";
else
{
char static out[2000]={'b', 'a'};
int idx=2, prev=1, tmp;
n-=2;
while(n--)
{
/* invariant: all values start at the beginning of `out`.
idx: keep the length of the current object
prev: keep the size of previous object
*/
memcpy(out+idx, out, prev);
tmp=prev;
prev=idx;
idx+=tmp;
}
return out;
}
}
int main()
{
int x;
printf("Enter the fibonacci nword number you want to see:"
"(f(x), f(0) is the starting element.):\n");
scanf("%d",&x);
printf("Required Word is:\n");
printf("~~%s\n", fib(x));
return 0;
}

How to count non-zero occurrences of a char in C?

I am new in C programming. I would like to ask how I can store a char in a char array? The reason why I want to do it is because I get a char from a computation I make. This computation returns a char consisting of 4. I want to look through every character of the 4 and check if they are "0". If not, then I will increment by one. This is an example of a substitution: "0xf3"- I am trying to compute the Hamming Weight of a substitution. This is how I try to count how many non-zero the char consists of:
#include <stdio.h>
int main()
{
char x = "0xf3";
char s[10] = x;
int lingh = strlen(s);
for (int i = 0; i<lingh;i++) {
printf("%c\n", s[i] );
}
return 0;
}
the output I expect is something like s[] = {0,x,f,3}
This computation returns a char consisting of 4.
You are saying your computation returns a character which consists of 4 characters. Is it possible???
I guess your computation returns a string that consists of 4 characters. Example 0xf3
You can not store a string literal in char type variable.
char x = "0xf3"; //<---------------------
You can store them in a character array like char x[] = "0xf3";
Here is the modified code
#include <stdio.h>
#include<string.h> //<---- for strlen() and strcpy()
int main()
{
char x[] = "0xf3"; //<----store in a char array
char s[10];
strcpy(s, x); //<----copy in another array
int lingh = strlen(s);
for (int i = 0; i<lingh;i++) {
printf("%c\n", s[i] );
}
return 0;
}

How to use pointer to split the string into two strings? C language

The function char *my(char *s, int n) takes a string s and shifts the characters of s by n places, causing the characters to wrap around the string.
For example, given the string "This is my Apple!" , a shift of n = 2 will result in
String1: "Th"
String2: "is is my Apple!"
if n<0 it will shift in negative direction.
You can just use printf to split a string. If you want the result in a char *, you have to allocate some memory and use sprintf instead.
Here is a example using sprintfand memory allocation to return a char *.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *shift(char *string, int n)
{
int len = strlen(string);
char *shiftedString = malloc(len + 1);
n %= len; // in case you shift over string length
if (n < 0) n += len; // backward shift
sprintf(shiftedString, "%s%*.*s", string + n, n, n, string);
return shiftedString;
}
int main()
{
char *result = shift("This is my Apple!", 2);
printf("shifted string : %s\n", result);
free(result);
return 0;
}
the string is actually a char-array char[]
you could use the strlen function in combination with a for loop like so.
You can put that in a function thus creating your own function that would shift letters based on input N.
#include <stdio.h>
#include <string.h>
int main()
{
char string[] = "This is my Apple!";
//Initialize "n" before initializing the string variables.
int n = 2;
int len = strlen(string);
char string1[n];
char string2[len - n];
for(int i = 0;i<len;i++){
if(i<n){
string1[i]=string[i];
}else{
string2[i-n]=string[i];
}
}
printf("string = %s\n",string);
printf("string1 = %s\n",string1);
printf("string2 = %s\n",string2);
return 0;
}

Strange printf output in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * reverse(char *string);
int main(int argc, char *argv[])
{
char array[10];
array[0] = 'a';
array[1] = 'b';
array[2] = 'c';
array[3] = 'd';
array[4] = 'e';
printf("1%s\n",array);
char *p = reverse(array);
printf("4%s\n",p);
printf("5%s\n",array);
}
char * reverse(char *string)
{
int size = strlen(string);
char reversed[size];
int i;
int j = 0;
for(i = size-1; i >= 0; i--)
{
reversed[j] = string[i];
j++;
}
printf("2%s\n",reversed);
string = reversed;
printf("3%s\n",string);
return reversed;
}
This code basically just initializes an array of values and passes it into a method that reverses these values.
I am not sure if this is the best way to execute the task, since I am new to pointers and arrays in C.
But the real question is this:
Can anyone figure out why in this line
printf("4%s\n",p);
if you remove the preceding '4', so it looks like so
printf("%s\n",p);
the line won't print at all?
You are returning a pointer to local variable(reversed) in the function reverse the question should actually be: Why did it work in the first place?.
This code string = reversed; will only copy the pointer, and again the local copy of the pointer so it has no effect outside the function.
To reverse a string you don't need additional memory - this can be done in-place.
Strings in C must end with the null character. You're using strlen on a non null-terminated string.
Furthermore, you just a very lucky person, because there is a serious problem with you code: you forget to add \0 symbol at the end of string.
UPD: the main problem is with code line char reversed[size];.
It's a regular local variable, it has automatic duration, which means that it springs into existence when the function is called and disappears when the function returns (see this link).
You need to change it to:
char *reversed = malloc((size+1)*sizeof(char));
UPD-2: another bug fixing will be:
1) add array[5] = '\0'; after all other array initializing lines
2) add reversed[j] = '\0'; after for...loop:
for(i = size-1; i >= 0; i--)
{
reversed[j] = string[i];
j++;
}
reversed[j] = '\0';
UPD-3: But in general it will much more correctly initialize your string in appropriate way:
char array[10] = "abcde";

Resources