some simple Pointers questions - c

Hi please kindly explain to me why is the code generating an error,
#include<stdio.h>
int main(){
char ***x;
char **q = *x;
char **(*c) = x;
char ***d = &q;
char ***p = "asdasd";
x=p;
printf("d:%s\n",d);
printf("q:%s\n",q);
printf("x:%s\n",x);
return 0;
}
Output:
1
Segmentation fault
Hi Thanks for the replys so if I init x, i still got an Segmentation fault on
printf("q:%s\n",q);
the output and code is shown below, please kindly advise why is d:1231 instead of 1231123124 and why x=p only change the value of x instead of all (x, q, d)
int main(){
char ***x = "1231123124";
char **q = *x;
char **(*c) = x;
char ***d = &q;
char ***p = "asdasd";
x=p;
printf("p:%s\n",p);
printf("d:%s\n",d);
// printf("q:%s\n",q);
printf("x:%s\n",x);
printf("c:%s\n",c);
return 0;
}
Output:
p:asdasd
d:1231
x:asdasd
c:1231123124

char **q = *x;
Here you are dereferencing an uninitialized pointer.
It's undefined behaviour, in this case it usually results a segfault (in practice your code will try to dereference some random memory location, or NULL if your compiler initializes local variables (this is typical for debug/non-optimized builds)).

These are type errors.
printf("d:%s\n",d); // d is char***, not char*
printf("q:%s\n",q); // q is char**, not char*
printf("x:%s\n",x); // x is char***, not char*
The %s specifier expects a char * argument, or possibly void *, const char *, etc., but never a char ** or char ***.

Related

What is the trick for swap_pointers to work?

I am doing an exercise where the task is to fix swap_pointer().
Two string should be swapped.
s1 = "I should print second.";
s2 = "I should print first.";
My work so far:
#include <stdio.h>
void swap_nums(int *, int *);
void swap_pointers(char *x, char *y);
int main(void) {
int a = 3, b = 4;
char *s1, *s2;
swap_nums(&a, &b);
printf("a is %d\n", a);
printf("b is %d\n", b);
s1 = "I should be printed second.";
s2 = "I should be printed first.";
/* swap_pointers(s1, s2); */
printf("s1 is %s\n", s1);
printf("s2 is %s\n", s2);
return 0;
}
void swap_nums(int *x, int *y) {
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
void swap_pointers(char *x, char *y) {
char tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
I think that not appending & to s1 and s2 before I pass them to the function for swap_pointers is the error?
If anyone can fix my issue here, please don't give the whole solution! I want to use what you give me as a tool to fix it by my own. If I really can't fix it by my own I will adress this later.
Ty in advance!
Let's at first consider this code snippet
int a = 3, b = 4;
swap_nums(&a, &b);
To swap the objects a and b you need to pass then to the function swap_nums by reference through pointers to them. Thus within the function dereferencing the pointers we can get a direct access to original objects and change their values.
void swap_nums(int *x, int *y) {
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
The same we need to do with the variables s1 and s2. That is we need to pass them to the function swap_pointers by reference through pointers to them.
So you need to write
swap_ponters( &s1, &s2 );
and the function will be declared and defined like
void swap_ponters(char **x, char **y)
{
char *tmp = *x;
*x = *y;
*y = tmp;
}
In general if you have two objects like
T a;
T b;
where T is some type specifier then to change the objects in a function you need to pass them to the function by reference through pointers to them. So the declaration of the function swap will look like
void swap( T *a, T *b );
and the function will be called like
swap( &a, &b );
In your program a and b has the type int, that is T is an alias for the type int.
typedef int T;
T a = 3, b = 4;
so the function declaration will look like
void swap_nums( T *x, T *y );
For the variables s1 and s2 you can write
typedef char *T;
T s1, s2;
and again the function declaration will look like
void swap_pointers( T *x, T *y );
and the function will be called like
swap_pointers( &s1, &s2 );
As in this case T is an alias for the type char * then the function declaration can be rewritten like
void swap_pointers( char * *x, char * *y );
Your pass the pointers to the first characters of two null-terminated strings to the swap_pointers function.
Inside the function, when you use e.g. *x it's the same as x[0].
So you're swapping the first character of x with the first character of y.
If you want to switch pointers, you need to emulate pass-by-reference like you do with swap_nums, and pass pointers to the pointers, i.e. char **. And use the pointer-to operator & in the call.
So it should be
void swap_ponters(char **x, char **y);
and
swap_pointers(&s1, &s2);

Pointer / dereference error

I want to display "string pointer affected" but I get an error. Here is my code:
#include<stdio.h>
main()
{
char* *p;
char * s="string pointer affected";
*p=s;
printf("%s",*p);
}
p doesn't point to any known location, so writing to *p is a bad idea.
You mean to say:
p = &s;
You dereference a pointer which is not initialized , which will cause undefined behaviour . This is problem -
*p=s;
You are using an uninitialized variable in the line below and in the printf statement. If you replace
*p = s;
with
p = &s;
then it will work.
Try:
#include<stdio.h>
main()
{
char *p; // <--------------------------
char *s="string pointer affected";
printf("===== s=%p\n", s);
p=s;
printf("===== p=%p\n", p);
printf("%s\n", p);
}
The problem with the original code is that p is uninitialized. So you cannot dereference it.
If you do want to use a pointer to a pointer, allocate the pointer first, and then take its address.
#include<stdio.h>
main()
{
char *q;
char **p = &q;
char *s="string pointer affected";
*p=s;
printf("%s\n", *p);
}

char pointer and printf 2

please advise me on the following output:
int main()
{
char ***x = "jjhljlhjlhjl";
char ***q = "asddfwerwerw";
**q = **x;
printf("x:%s\n",x);
printf("q:%s\n",q);
}
Output: 1 Segmentation fault
This is what you should have:
#include <stdio.h>
int main(void) {
char *x = "jjhljlhjlhjl";
char *q = "asddfwerwerw";
q = x;
printf("x:%s\n",x);
printf("q:%s\n",q);
return 0;
}
If you want to initialize a character string, use char *x
Don't use ***x. That means pointer to pointer to pointer to a char.
Hope that helps.
"Segmentation fault" is not an output, it's an indication that your program has crashed.
This should come as no surprise, because string literals are char*, not char***. Trying to double-derefefence such pointers is undefined behavior, because it re-interprets the content of a string literal as a pointer to char. This is what is causing the crash.
You can modify your program as follows to make it legal:
int main() {
char *x = "jjhljlhjlhjl";
char tmp[] = "asddfwerwerw";
char *q = tmp;
*q = *x;
// This will produce an output that should be easy to explain:
printf("x:%s\n",x);
printf("q:%s\n",q);
}

C segmentation fault-char pointers

I need help figuring out why I am getting a segmentation fault here. I have gone over it and I think I am doing something wrong with the pointers, but I can figure out what.
My Program:
#include <stdlib.h>
#include <stdio.h>
void encrypt(char* c);
//characters are shifted by 175
int main(){
char* a;
*a = 'a';
/*SEGMENTATION FAULT HERE!*/
encrypt(a);
printf("test:%c/n",*a);
return 0;
};
void encrypt(char* c){
char* result;
int i=(int)(*c);
i+=175;
if(i>255)
{
i-=256;
}
*c=(char)i;
};
The problem is here:
char *a;
*a = 'a'
Since the variable "a" is not initialized, *a = 'a' is assigning to a random memory location.
You could do something like this:
char a[1];
a[0] = 'a';
encrypt(&a[0]);
Or even just use a single character in your case:
int main(){
char a = 'a';
encrypt(&a);
printf("test:%c/n",a);
return 0;
};
char* a;
*a = 'a';
/*SEGMENTATION FAULT HERE!*/
There isn't any "there" there. You've declared a and left it uninitialized. Then you tried to use it as an address. You need to make a point to something.
One example:
char buffer[512];
char *a = buffer;
(Note buffer has a maximum size and when it falls out of scope you cannot reference any pointers to it.)
Or dynamic memory:
char *a = malloc(/* Some size... */);
if (!a) { /* TODO: handle memory allocation failure */ }
// todo - do something with a.
free(a);
That pointer a does not get the actual space where to store the data. You just declare the pointer, but pointing to where? You can assign memory this way:
char *a = malloc(1);
Then it won't segfault. You have to free the variable afterwards:
free(a);
But in this case, even better,
char a = 'a';
encript(&a);

Problem with C char[] swapping

I have this short code:
#include <stdio.h>
void fastSwap (char **i, char **d)
{
char *t = *d;
*d = *i;
*i = t;
}
int main ()
{
char num1[] = "hello";
char num2[] = "class";
fastSwap ((char**)&num1,(char**)&num2);
printf ("%s\n",num1);
printf ("%s\n",num2);
return 0;
}
The output of this short program is:
claso
hells
and I just don't understand why the last letters of each char[] are swapped.
Any ideas?
fastSwap ((char**)&num1,(char**)&num2);
This is undefined behavior. You can't cast a pointer to array of char to a pointer to pointer to char. What you need is:
const char* num1 = "hello";
const char* num2 = "class";
fastSwap (&num1,&num2);
Also, you'll need to change the declaration of fastSwap and add inner-level const to arguments
void fastSwap (const char **i, const char **d)
I'm assuming you're trying to swap the contents of the num1 and num2 arrays by just manipulating pointers, so that after calling fastswap the contents of num1 will be "class" and num2 will be "hello".
If that's the case, then this won't work for a number of reasons. Arrays are not pointers, even though array expressions are often converted to pointer types. Secondly, you cannot modify the value of an array expression.
If you want to keep num1 and num2 as arrays (as opposed to pointers to string literals) and be able to swap their contents, you'll need to something more along these lines:
void fastswap(char *i, char *d)
{
while (*i && *d)
{
char t = *i;
*d++ = *i;
*i++ = t;
}
}
which will be called as
fastswap(num1, num2);
You are passing pointers to pointers to chars. You probably just want to pass pointers to chars like this:
#include <stdio.h>
void fastSwap (char *i, char *d)
{
char t = *d;
*d = *i;
*i = t;
}
int main ()
{
char num1[] = "hello";
char num2[] = "class";
fastSwap (num1,num2);
printf ("%s\n",num1);
printf ("%s\n",num2);
return 0;
}
This swaps the first character of the 2 char arrays.

Resources