Is it possible to convert char[] to char* in C? - c

I'm doing an assignment where we have to read a series of strings from a file into an array. I have to call a cipher algorithm on the array (cipher transposes 2D arrays). So, at first I put all the information from the file into a 2D array, but I had a lot of trouble with conflicting types in the rest of my code (specifically trying to set char[] to char*). So, I decided to switch to an array of pointers, which made everything a lot easier in most of my code.
But now I need to convert char* to char[] and back again, but I can't figure it out. I haven't been able to find anything on google. I'm starting to wonder if it's even possible.

It sounds like you're confused between pointers and arrays. Pointers and arrays (in this case char * and char []) are not the same thing.
An array char a[SIZE] says that the value at the location of a is an array of length SIZE
A pointer char *a; says that the value at the location of a is a pointer to a char. This can be combined with pointer arithmetic to behave like an array (eg, a[10] is 10 entries past wherever a points)
In memory, it looks like this (example taken from the FAQ):
char a[] = "hello"; // array
+---+---+---+---+---+---+
a: | h | e | l | l | o |\0 |
+---+---+---+---+---+---+
char *p = "world"; // pointer
+-----+ +---+---+---+---+---+---+
p: | *======> | w | o | r | l | d |\0 |
+-----+ +---+---+---+---+---+---+
It's easy to be confused about the difference between pointers and arrays, because in many cases, an array reference "decays" to a pointer to it's first element. This means that in many cases (such as when passed to a function call) arrays become pointers. If you'd like to know more, this section of the C FAQ describes the differences in detail.
One major practical difference is that the compiler knows how long an array is. Using the examples above:
char a[] = "hello";
char *p = "world";
sizeof(a); // 6 - one byte for each character in the string,
// one for the '\0' terminator
sizeof(p); // whatever the size of the pointer is
// probably 4 or 8 on most machines (depending on whether it's a
// 32 or 64 bit machine)
Without seeing your code, it's hard to recommend the best course of action, but I suspect changing to use pointers everywhere will solve the problems you're currently having. Take note that now:
You will need to initialise memory wherever the arrays used to be. Eg, char a[10]; will become char *a = malloc(10 * sizeof(char));, followed by a check that a != NULL. Note that you don't actually need to say sizeof(char) in this case, because sizeof(char) is defined to be 1. I left it in for completeness.
Anywhere you previously had sizeof(a) for array length will need to be replaced by the length of the memory you allocated (if you're using strings, you could use strlen(), which counts up to the '\0').
You will need a make a corresponding call to free() for each call to malloc(). This tells the computer you are done using the memory you asked for with malloc(). If your pointer is a, just write free(a); at a point in the code where you know you no longer need whatever a points to.
As another answer pointed out, if you want to get the address of the start of an array, you can use:
char* p = &a[0]
You can read this as "char pointer p becomes the address of element [0] of a".

If you have
char[] c
then you can do
char* d = &c[0]
and access element c[1] by doing *(d+1), etc.

You don't need to declare them as arrays if you want to use use them as pointers. You can simply reference pointers as if they were multi-dimensional arrays. Just create it as a pointer to a pointer and use malloc:
int i;
int M=30, N=25;
int ** buf;
buf = (int**) malloc(M * sizeof(int*));
for(i=0;i<M;i++)
buf[i] = (int*) malloc(N * sizeof(int));
and then you can reference buf[3][5] or whatever.

None of the above worked for me except strtok
#include <string.h>
Then use strtok
char some[] = "some string";
char *p = strtok(some, "");
strtok is used to split strings. But you can see that I split it on nothing ""
Now you have a pointer.

Well, I'm not sure to understand your question...
In C, Char[] and Char* are the same thing.
Edit : thanks for this interesting link.

Related

Is a char array more efficient than a char pointer in C?

I'm trying to understand the under-the-hood difference between these two char declarations:
char* str1;
char str2[10];
I understand that using char* gives a pointer to the first character in str1, while char[10] results in an array with a length of 10 bytes (because char is a single byte... I recall that in some encodings it can be more but let's just assume one byte to keep it simple).
My question is when actually assigning values to them the data obviously has to be stored somewhere and in the case of char[10] we're telling the compiler upfront to allocate ten bytes, whereas in the case of char* we're really just saying allocate a pointer to a single byte. But what happens if the string we assign to str1 is more than a single byte, how is that allocated? How much more work is needed to appropriately allocate that? Plus, what happens if we want to reassign str1 to be something longer than what was previously assigned, how is that allocated?
Because of the uncertainty from the compiler's point of view when dealing with char pointers, is it more efficient to use a char array when I either know the length ahead of time or want to limit the length to start with?
When discussing performance in general, allocation, access time and copy time separate things. You seem mostly concerned about allocation.
But there are lots of misconceptions here. Arrays are used for storing. Pointers are used to point at things stored elsewhere. You cannot store any data in a pointer, you can only store an address to data allocated elsewhere.
So comparing pointers or arrays is pretty much nonsense, because they are separate things. Similar to "should I live in my house at a street address or should I live in the sign stating my street address".
I understand that using char* gives a pointer to the first character in str1
No, it gives a pointer to a single character which is allocated somewhere else. Though it doesn't point anywhere meaningful until you assign an address to it. In case of arrays, it will typically get set to point at the first character of the array.
I recall that in some encodings it can be more
No, a character is per definition always 1 byte. Some exotic systems might have 16 bits per bytes or such though. This is of no concern unless you program exotic DSPs and the like. As for other character encodings, there's wchar_t which is a different topic entirely.
whereas in the case of char* we're really just saying allocate a pointer to a single byte
No, we tell it to allocate room for the pointer itself. Which is typically of a size between 2 to 8 bytes depending on address bus width of the specific system.
But what happens if the string we assign to str1 is more than a single byte, how is that allocated?
However you like. You can assign it to a read-only string literal, or a static storage duration variable, or a local automatic storage variable, or dynamically allocated variables. The pointer itself doesn't know or care.
How much more work is needed to appropriately allocate that?
It depends on what you want to allocate.
Because of the uncertainty from the compiler's point of view when dealing with char pointers
What uncertainty is that? Pointers are pointers and the compiler don't treat them much differently than other variables.
is it more efficient to use a char array when I either know the length ahead of time or want to limit the length to start with?
You need to use an array, because data cannot be stored in thin air. Again, data cannot be stored "in pointers".
But what happens if the string we assign to str1 is more than a single byte, how is that allocated?
str1 ultimately has to point to another array of char - whether it's allocated automatically, such as
char buffer[10];
char *str1 = buffer; // equivalent to &buffer[0]
or dynamically:
char *str1 = malloc( sizeof *str1 * 10 );
or through some other method. All str1 stores is the address of a char object somewhere in memory. You're not actually saving anything to str1, you're saving it to whatever str1 points to. Assume the following declarations:
char *str;
char buffer[10];
We have something like this in memory:
char * char
+---+ +---+
str: | ? | buffer: | ? | buffer[0]
+---+ +---+
| ? | buffer[1]
+---+
...
+---+
| ? | buffer[9]
+---+
First, we assign the address of the first element of buffer to str1:
str = buffer;
Now our picture looks like this:
char * char
+---+ +---+
str: | | --> buffer: | ? | buffer[0]
+---+ +---+
| ? | buffer[1]
+---+
...
+---+
| ? | buffer[9]
+---+
Now we can store a string in buffer using str:
strcpy( str, "foo" );
giving us
char * char
+---+ +---+
str: | | --> buffer: |'f'| buffer[0]
+---+ +---+
|'o'| buffer[1]
+---+
|'o'| buffer[2]
+---+
| 0 | buffer[3]
+---+
...
+---+
| ? | buffer[9]
+---+
"So," you're asking yourself, "why do we bother with the pointer? Why not just store the string to buffer directly? Wouldn't that be more efficient?"
Yes, normally we would just store to buffer directly and avoid the overhead of the pointer if that was an option. Sometimes, however, it isn't an option. We work through pointers in the following situations:
The array was allocated dynamically - in this case we have no option but to go through a pointer:char *str = malloc( sizeof *str * 10 );
strcpy( str, "foo" );
The array was passed as an argument to a function - because of the decay rule, when a you pass an array as a function argument what the function actually receives is a pointer to the first element (this is true of all array types, not just character arrays):void foo( char *str, size_t max_size )
{
strncpy( str, "this is a test", max_size );
str[max_size-1] = 0;
}
We're using a pointer to iterate through an array of char [] or char *:char table[][10] = { "foo", "bar", "bletch", "blurga", "" };
...
char *p = table[0];
while ( strlen( p ) )
printf( "%s\n", p++ );
...
Of course, we could just use array notation and not bother with the pointer at all:size_t i = 0;
while ( strlen( table[i] ) )
printf( "%s\n", table[i++] );
Sometimes using array notation makes more sense, sometimes using a pointer makes more sense - depends on the problem at hand.
Unless it is the operand of the sizeof or unary & operator, or it is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of `T`" will be converted, or "decay", to an expression of type "pointer to `T`" and the value of the expression will be the address of the first element of the array.
char* str1; is declaring str1 as a pointer to a char data type. It doesn't allocate memory for a byte. But compiler allocates sizeof(char*) bytes for this variable.
str1 can be used to point to any char * data type. For example, a string literal or a char array terminated with \0.
I don't know what do you mean by Is a char array more efficient than a char pointer. Both data types are different and have different use cases.
Asking this question sounds like asking Is an int type more efficient than a double type? It doesn't make any sense.
On the other hand, char[10] str2; is not a valid C syntax. I guess you mean char str2[10]; and this declares str2 as an array of 10 char. This variable can store 10 char data types.
str1 and str2 are two different data types.
Ok, let's go through your question piece by piece.
char* str1; //this is a pointer
char str2[10]; //that is an array of 10 characters
char[10] str2; //that is compilation error
//possibly your mistook C for Java
I understand that using char* gives a pointer to the first character in str1
char* str1 is a pointer to a character. It can point to contiguous memory location, e.g. a C-style string, but doesn't have to. It might point to a single character as well.
while char[10] results in an array with a length of 10 bytes (because
char is a single byte... I recall that in some encodings it can be
more but let's just assume one byte to keep it simple).
Yes, that is correct. Depending on where it is defined, the array can be located on the stack, or in the data segment (if it's a global); that's an implementation detail though.
My question is when actually assigning values to them the data obviously has to be stored somewhere and in the case of char[10] we're telling the compiler upfront to allocate ten bytes (...)
That's generally right.
But what happens if the string we assign to str1 is more than a single
byte, how is that allocated? How much more work is needed to
appropriately allocate that? Plus, what happens if we want to reassign
str1 to be something longer than what was previously assigned, how is
that allocated?
It really depends on the case. Given the following case:
char s1[] = "foo";
char s2[] = "bar";
char* ptr;
ptr = &s1[1]; //points to first o
ptr = &s2[2]; //points to r
nothing is really allocated. Simply the contents of ptr changes, the same way an integer would.
Note that it can be dereferenced/passed as a C-style string in this case.
However, in the following one, it cannot:
char c1 = 'a';
char c2 = 'b';
char* ptr;
ptr = &c1; //points to a
ptr = &c2; //points to b
Now, in case of immediate strings:
const char* s = "foo"; //should be const char* actually
the string is stored in the binary most likely as a global const and the s points to its start.
A mental model for it might be similar to:
//globals
const char someCompilerGeneratedName[] = "foo";
//then the pointer:
const char* s = &someCompilerGeneratedName[0];
//Note that arrays decay to pointers,
//i.e. array name denotes address of its 1st element
//the one below is equivalent:
const char* s = someCompilerGeneratedName;
Now, the pointer can post also to dynamically allocated memory.
But it does not have to.
So the following code
char single = 'c';
char* c1 = malloc(10*sizeof(char));
char* c2;
c2 = c1;
c2 = &single;
is perfectly valid.
From performance standpoint:
measure first. There is no easy answer here.
Now if you're asking about heap vs stack allocations, that's another story. But I'd say: measure first. Heap allocations are generally believed to be slower (often they are), but oftentimes their overhead is negligible anyway.
Also, keep in mind that
*(p+2) = //whatever else
is equivalent to:
p[2] = //whatever else
so sometimes it might be just the case of readability.
Arrays used in expressions is implicitly converted (with rare exceptions) to pointers to their first elements. So for example if you write
char[10] str2 = "Hello";
char* str1 = str2;
then these class of puts
puts( str2 );
puts( str1 );
will be equivalently efficient the same way is to write
for ( size_t i = 0; str2[i] != '\0'; i++ )
{
putchar( str2[i] );
}
and
for ( size_t i = 0; str1[i] != '\0'; i++ )
{
putchar( str1[i] );
}
A difference can occur in these declarations
char[10] str2 = "Hello";
char* str1 = "Hello";
In the first case the array str2 is initialized by a string literal and you may change the stored string as for example
str2[0] = 'h';
In the second case the pointer str1 points to a string literal that has static storage duration and may not be changed. So if you will write
str1[0] = 'h';
then this statement will invoke undefined behavior.
On the other hand, if you will write the following function
char * f( void )
{
char str2[10] = "Hello";
return str2;
}
then the returned pointer will be invalid because the declared array will not be alive after exiting the function.
But this function
char * f( void )
{
char* str1 = "Hello";
return str1;
}
will be correct because the string literal having static storage duration will be alive after exiting the function.
Also if you will declare
char* str1 = "Hello";
then the expression sizeof( str1 ) will yield the size of the pointer that is equal to either 4 or 9 dependent on the used system.
But if you will write
char str2[10] = "Hello";
then the expression sizeof( str2 ) will yield the size of the array that is equal to 10.
However this function calls
strlen( str1 );
and
strlen( str2 );
equivalently effective and the both will return the value 5 that is the length of the string "Hello".
There are enough answers explaining the miscellaneous aspects.
When C++ came first with the STL libraries, undermore string, we did have a speed and memory problem: really many strings.
So I made my own implementation of string with both:
char* ptr_to_actual_content;
char small_content[16];
ptr_to_actual_content = size < sizeof(small_content) ? small_content : malloc(size);
As now for small strings no extra allocation happened, the performance and speed gain was unbelievable huge. (By the way, NO memory leaks.)
Is a char array more efficient than a char pointer in C?
This is really an impossible question to answer. There is no inherent efficiency of an array or a pointer. One or the other may have better or worse efficiency for a particular operation, under a particular compiler, for a particular processor architecture. But there are no absolute guarantees.
What's equally important is that one or the other may have better or worse functionality for the problem at hand. Or better or worse convenience for you, the programmer. These factors are hugely important, too, likely more important than raw efficiency.
My advice to you is that you really learn the different ways of using arrays and pointers in C, and — most importantly — really understand the concept of the "correspondence between arrays and pointers". Only after gaining that understanding, I think, will you be in a position to make any meaningful distinctions between which one might be "more efficient" for a particular problem. Realize, too, that the actual efficiency differences, if any, might be immeasurably slight.
In terms of raw allocation, it's always going to be faster to allocate an array (which mostly happens at compile time, and has almost no run-time overhead [footnote]) than to call malloc to dynamically allocate some memory to point to. (But, much of the time, there will be an overwhelming preference towards dynamic memory allocation anyway, because of the intolerable nuisance of fixed, compile-time limits.)
In terms of copying, there will not generally be any difference whatsoever between any of the calls
memcpy(a, p, n);
memcpy(p, a, n);
memcpy(a1, a2, n);
memcpy(p1, p2, n);
for arrays a and pointers p. On the other hand, the best way to speed up memory copying is to not copy memory around at all, so in once sense pointers can be hugely more efficient, in that they let you do things like
p = a;
and
p1 = p2;
instead (which you obviously can't do for arrays).
Finally, there's the question of raw access. Down at the machine language level, there is going to be a significant difference between the instructions required to do
x = a[i];
versus
y = p[i];
But I can't tell you which will be faster, because it tends to vary from processor to processor and compiler to compiler.
People used to worry whether it was faster to iterate over an entire array using "array style":
for(i = 0; i < n; i++)
sum += a[i];
or "pointer style":
for(p = a; p < &a[n], p++)
sum += *p;
Once upon a time, one of these was likely to be significantly more efficient — although, again, the answer depended on the processor architecture, and tended to vary over time. Today, I believe that optimizing compilers are smart enough to choose the most efficient machine code to emit regardless of which way you write the C code.
Finally, as is always the case when asking "Which is more efficient?", the only way to find an actual answer is to code it up, for your problem statement and using your compiler and your processor, and perform careful measurements. There are so many factors that go into the efficiency question that it's usually impossible to make accurate predictions.
Footnote: I said that array allocation "mostly happens at compile time, and has almost no run-time overhead". There's one exception, which concerns large arrays which are local to functions. Those can take significant time to "allocate" if the OS has to assign a bunch more stack space at the last minute, and they can also fail if they're too big. So large, local arrays are generally disrecommended.

Memory allocation for pointer to a char array

would someone please explain the difference between
char *names[3]
and
char (*names)[3]
and how to read this operators?
If I want to allocate memory for them dynamically how to do so?
For the first case, I think it's just an array of char* of length 3, so no memory allocation not applicable. But in second case how to do memory allocation?
When faced with questions like this, you can usually turn to cdecl (online version here):
cdecl> explain char *names[3]
declare names as array 3 of pointer to char
cdecl> explain char (*names)[3]
declare names as pointer to array 3 of char
So the former creates array of three pointers-to-char:
+----------+
| names[0] | -> char
| [1] | -> char
| [2] | -> char
+----------+
And the latter creates a single pointer to a char array of size three.
+-------+
| names | -> char, char, char - no, not a dance step :-)
+-------+
The second line decodes as "declare names as pointer to array 3 of char".
I've been writing C for over 25 years, and I've never used such a variable.
Anyway, I guess this should work:
char data[3];
char (*names) = data;
Note that the variable name, names, is highly misleading since the variable holds only 3 single characters, as opposed to char *names[3] which is three pointers to characters and thus easily could be used to hold three strings.
Also note that the above code makes little sense, you could just use data directly if you had it.
The first an array of three pointers to char.
The second is a pointer to an array of three chars.
(Read it as "*names is a char[3]").
You can create such a pointer by taking the address of an array of three chars:
char name[3];
char (*names)[3] = &name;
or dynamically in the normal way:
char (*names)[3] = malloc(sizeof(*names)); /* or sizeof(char[3]), if you're fond of bugs */
or through the regular array-to-pointer conversion:
char stuff[2][3] = {};
char (*names)[3] = stuff; /* Same as &stuff[0], as normal. */
and how to read this operators?
Let's take the second one as it is the more complex of the two:
char (*names)[3];
When you are looking at a complex definition like this, the best way to attack it is to start in the middle and work your way out. “Starting in the middle” means starting at the variable name, which is names.
“Working your way out” means looking to the right for the nearest item (nothing in this case; the right parenthesis stops you short), then looking to the left (a pointer denoted by the asterisk), then looking to the right (an array of 3), then looking to the left (char).
This right-left-right motion works with most declarations.
This means names is a pointer to an char array of size 3.
This is very strange declaration but that is how it is read.
If I want to allocate memory for them dynamically how to do so?
Now that you know what the declaration means, memory allocation becomes easy:
char (*names)[3] = malloc(3 * sizeof(char));
char *names[3] is an array of 3 char pointers.
char (*names)[3] is an array pointer (pointer to array) to an array of 3 characters char[3].
So these two have fundamentally different meanings! Don't confuse them with each other.
If you wish to allocate an array of pointers, then you can do it as in either of these examples:
char** names = malloc(3 * sizeof(*names) );
char** names = malloc(sizeof(char*[3]));
char** names = calloc(3, sizeof(char*));
These are all equivalent (but calloc also sets all pointers to NULL). names will be a pointer to the first element in the array. It will be a pointer to a char*.
If you wish to allocate an array and point to the first element, simply do:
char* names = malloc(3 * sizeof(*names));
Alternatively, you can use the array pointer syntax and point to the array as whole:
char (*names)[3] = malloc(sizeof(*names));

Why this simple program in C crashes (array VS pointer)

I have two files:
In file 1.c I have the following array:
char p[] = "abcdefg";
In file 0.c I have the following code:
#include <stdio.h>
extern char *p; /* declared as 'char p[] = "abcdefg";' in 1.c file */
int main()
{
printf("%c\n", p[3]); /* crash */
return 0;
}
And this is the command line:
gcc -Wall -Wextra 0.c 1.c
I know that extern char *p should've been: extern char p[];, but I just want an explanation of why it doesn't work in this particular case. While it works here:
int main()
{
char a[] = "abcdefg";
char *p = a;
printf("%c\n", p[3]); /* d */
return 0;
}
Your two examples are not comparable.
In your second example, you have
char a[] = "abcdefg";
char *p = a;
So a is an array, and p is a pointer. Drawing that in pictures, it looks like
+---+---+---+---+---+---+---+---+
a: | a | b | c | d | e | f | g | \0|
+---+---+---+---+---+---+---+---+
^
|
+----|----+
p: | * |
+---------+
And this is all fine; no problems with that code.
But in your first example, in file 1.c you define an array named p:
+---+---+---+---+---+---+---+---+
p: | a | b | c | d | e | f | g | \0|
+---+---+---+---+---+---+---+---+
You can name an array "p" if you want (the compiler certainly doesn't care), but then, over in file 0.c, you change your mind and declare that p is a pointer. You also declare (with the "extern" keyword) that p is defined somewhere else. So the compiler takes your word for it, and emits code that goes to location p and expects to find a pointer there -- or, in pictures, it expects to find a box, containing an arrow, that points somewhere else. But what it actually finds there is your string "abcdefg", only it doesn't realize it. It will probably end up trying to interpret the bytes 0x61 0x62 0x63 0x64 (that is, the bytes making up the first part of the string "abcdefg") as a pointer. Obviously that doesn't work.
You can see this clearly if you change the printf call in 0.c to
printf("%p\n", p);
This prints the value of the pointer p as a pointer. (Well, of course, p isn't really a pointer, but you lied to the compiler and told it that it was, so what you'll see is the result when the compiler treats it as a pointer, which is what we're trying to understand here.) On my system this prints
0x67666564636261
That's all 8 bytes of the string "abcdefg\0", in reverse order. (From this we can infer that I'm on a machine which (a) uses 64-bit pointers and (b) is little-endian.) So if I tried to print
printf("%c\n", p[3]);
it would try to fetch a character from location 0x67666564636264 (that is, 0x67666564636261 + 3) and print it. Now, my machine has a fair amount of memory, but it doesn't have that much, so location 0x67666564636264 doesn't exist, and therefore the program crashes when it tries to fetch from there.
Two more things.
If arrays are not the same as pointers, how did you get away with saying
char *p = a;
in your second example, the one I said was "all fine; no problems"?
How can you assign an array on the right-hand side to a pointer on the left?
The answer is the famous (infamous?) "equivalence between arrays and pointers in C": what actually happens is just as if you had said
char *p = &a[0];
Whenever you use an array in an expression, what you get is actually a pointer to the array's first element, just as I showed in the first picture in this answer.
And when you asked, "why it doesn't work, while it works here?", there were two other ways you could have asked it.
Suppose we have the two functions
void print_char_pointer(char *p)
{
printf("%s\n", p);
}
void print_char_array(char a[])
{
printf("%s\n", a);
}
And then suppose we go back to your second example, with
char a[] = "abcdefg";
char *p = a;
and suppose that we call
print_char_pointer(a);
or
print_char_array(p);
If you try it, you'll find that there are no problems with either of them.
But how can this be? How can we pass an array to a
function that expects a pointer, when we call print_char_pointer(a)?
And how can we pass a pointer to a
function that expects an array, when we call print_char_array(p)?
Well, remember, whenever we mention an array in an expression,
what we get is a pointer to the array's first element. So when
we call
print_char_pointer(a);
what we get is just as if we had written
print_char_pointer(&a[0]);
What actually gets passed to the function is a pointer, which is
what the function expects, so we're fine.
But what about the other case, where we pass a pointer to a function that's declared as if it accepts an array? Well, there's actually another tenet to the "equivalence between arrays and pointers in C".
When we wrote
void print_char_array(char a[])
the compile treated it just as if we had written
void print_char_array(char *a)
Why would the compiler do such a thing? Why, because it knows
that no array will ever be passed to a function, so it knows that no
function will actually ever receive an array, so it knows that the
function will receive a pointer instead. So that's the way the
compiler treats it.
(And, to be very clear, when we talk about the "equivalence
between arrays and pointers in C", we are not saying that
pointers and arrays are equivalent, just that there is this
special equivalence relationship between them. I've mentioned
two of the tenets of that equivalence already. Here are all
three of them, for reference: (1) Whenever you
mention the name of an array in an expression, what you
automatically get is a pointer to the array's first element.
(2) Whenever you declare a function that seems to accept an
array, what it actually accepts is a pointer. (3) Whenever you
use the "array" subscripting operator, [], on a pointer, as in
p[i], what you actually get is just as if you had written *(p + i). And, in fact, if you think about it carefully, due to
tenet (1), even when you use the array subscripting operator on
something that looks like an array, you're actually using it on a
pointer. But that's a pretty strange notion, which you don't
have to worry about if you don't want to, because it just works.)
Because arrays are not pointers. You tell the program "elsewhere I have a char pointer", but you actually don't have one - you have an array.
An array will decay into a pointer when used in an expression, but that doesn't mean that an array is a pointer. For more info see Is an array name a pointer?.
In your second example you have both an array and a pointer, two separate variables, so it is a different case.
Let me explain it in reverse:
In the second case, you have an array and then a pointer which points to that array.
Accessing via the pointer involves an indirect memory address ("print the 3rd byte from where this pointer points to" vs. "print the 3rd byte of this array").
In the first case, you have an array somewhere else, but tell the compiler you had a pointer at that place. So it tries to read that pointer and read the data from where it points to. But there is no pointer – there is the data immediately, so the pointer points to "anywhere and nowhere" (at least, quite likely). This constitutes undefined behaviour (often abbreviated as UB).

C: append char* to char**

I'm really new to C pointers and I'm coming from Java/C++. I am trying to append a char* c to a char** cArray. Here is kind of what I have so far:
char **cArray = "abc";
char *c = "def";
cArray += &c;
printf("%s", cArray)
and output should be: abcdef
My question is, How do I append a char * to a char ** in C?
Thank you for any tips you have!
You seem to have a misunderstanding of what a pointer and an array are. First lets start with an array. An array is a contiguous fixed-size block of memory. That is to say, an array is a constant number of values next to each other.
So, to start with, the idea of "Appending" an array makes sense in the way that you can add an item to the next empty spot in an array. But it would not be right to say the array is growing. An array is not the equivalent of Java's Array List.
Lastly, I will point out static arrays are declared with:
int val[3];
Where 3 can be any other constant value interpreted as a size_t.
Next, lets discuss pointers. Pointers are not arrays, do not confuse the two- although many people find it comforting to think of them as interchangeable (and for the most part you can get away with it!). However, this is one of the cases where they are not. So what are pointers?
Pointers denote the location of a value in memory. So, a pointer could say point to an element in our val array we created above. If we created a pointer to point at each element in our val array and we printed them all to stdout we would see that they are all 4 bytes away from each other. This is because arrays have their values located right next to each other (contiguous in memory) and sizeof(int) would return 4 (on my system).
Your main misunderstanding seems to be that pointers need to point to anything at all. They do not. Just like you can have a value which holds no information (or all of the bits are set to 0), you can surely have a pointer that points no nowhere at all. As a matter of fact that's exactly what you do.
char **cArray = "abc";
char *c = "def";
cArray += &c;
printf("%s", cArray);
Okay, lets take this apart line by line. First you declare a char ** called cArray and initialize it to "abc". Well, your variable cArray is a pointer to a pointer. The value "abc" I believe is a const char*. Therefore, you probably don't want to assign a pointer to a character as a pointer to a pointer. The consequence being, the value "abc\0" will be interpreted as another memory address. This, obviously, will not point to anything useful and accessing this memory would result in a seg fault.
Next, you initialize c to be a cstring containing "def".
Finally, you increment the address pointed to by cArray by whatever address "def" happens to be located at. So now, cArray is no longer even pointing to "abc" at all (nevermind interpreting it incorrectly).
Then we try to print some block of memory pointed to by cArray that is in no way even remotely close to any of the bits our program wants to be touching.
All of this said, say I had two cstrings and I wanted to get a third such that it is the first appended to the second:
char* a = "abc";
char* b = "def";
size_t sizeA = strlen(a);
size_t sizeB = strlen(b);
size_t size = sizeof(char) * (sizeA + sizeB + 1); //Size of our new memory block large enough to contain both a and b.
//Leave additional space for null terminator
char* c = malloc(size); //Actually allocate new memory
memcpy(c, a, sizeA); //Copy a into the first half of c
memcpy(c + sizeA, b, sizeB); //Copy b into the second half
c[sizeA + sizeB] = '\0'; //Assign null terminator to last character
printf("%s", c);
free(c); //Never forget

Difference between char a[]="string"; char *p="string"; [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
What is the difference between char s[] and char *s in C?
What is the difference between char a[]="string"; and char *p="string";?
The first one is array the other is pointer.
The array declaration "char a[6];" requests that space for six characters be set aside, to be known by the name "a." That is, there is a location named "a" at which six characters can sit. The pointer declaration "char *p;" on the other hand, requests a place which holds a pointer. The pointer is to be known by the name "p," and can point to any char (or contiguous array of chars) anywhere.
The statements
char a[] = "hello";
char *p = "world";
would result in data structures which could be represented like this:
+---+---+---+---+---+---+
a: | h | e | l | l | o |\0 |
+---+---+---+---+---+---+
+-----+ +---+---+---+---+---+---+
p: | *======> | w | o | r | l | d |\0 |
+-----+ +---+---+---+---+---+---+
It is important to realize that a reference like x[3] generates different code depending on whether x is an array or a pointer. Given the declarations above, when the compiler sees the expression a[3], it emits code to start at the location "a," move three past it, and fetch the character there. When it sees the expression p[3], it emits code to start at the location "p," fetch the pointer value there, add three to the pointer, and finally fetch the character pointed to. In the example above, both a[3] and p[3] happen to be the character 'l', but the compiler gets there differently.
You can use search there are tons of explanations on the subject in th internet.
char a[]="string"; //a is an array of characters.
char *p="string";// p is a string literal having static allocation. Any attempt to modify contents of p leads to Undefined Behavior since string literals are stored in read-only section of memory.
No difference. Unless you want to actually write to the array, in which case the whole world will explode if you try to use the second form. See here.
First declaration declares an array, while second - a pointer.
If you're interested in difference in some particular aspect, please clarify your question.
One difference is that sizeof(a)-1 will be replaced with the length of the string at compile time. With p you need to use strlen(p) to get the length at runtime. Also some compilers don't like char *p="string", they want const char *p="string" in which case the memory for "string" is read-only but the memory for a is not. Even if the compiler does not require the const declaration it's bad practice to modify the string pointed to by p (ie *p='a'). The pointer p can be changed to point to something else. With the array a, a new value has to be copied into the array (if it fits).

Resources