Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about pointers and strings in C [duplicate]

Possible Duplicate:
What is the difference between char s[] and char *s in C?
Difference between char *str = “…” and char str[N] = “…”?

I have some code that has had me puzzled.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  char* string1 = "this is a test";
  char string2[] = "this is a test";
  printf("%i, %i\n", sizeof(string1), sizeof(string2));
  system("PAUSE"); 
  return 0;
}

When it outputs the size of string1, it prints 4, which is to be expected because the size of a pointer is 4 bytes. But when it prints string2, it outputs 15. I thought that an array was a pointer, so the size of string2 should be the same as string1 right? So why is it that it prints out two different sizes for the same type of data (pointer)?

like image 359
John Jacquay Avatar asked Dec 07 '10 18:12

John Jacquay


People also ask

How do you copy a string using pointers?

strcpy(): Using the inbuilt function strcpy() from string. h header file to copy one string to the other. strcpy() accepts a pointer to the destination array and source array as a parameter and after copying it returns a pointer to the destination string.

Which of the function is used in duplicating a string?

The strcpy() function copies the string pointed by source (including the null character) to the destination. The strcpy() function also returns the copied string.

Which function is used to duplicate the given string in C?

The C library function to copy a string is strcpy(), which (I'm guessing) stands for string copy. Here's the format: char * strcpy(char * dst, const char * src);

What is the relationship between pointers and strings in C?

Pointer to string in C can be used to point to the starting address of the array, the first character in the array. These pointers can be dereferenced using the asterisk * operator to identify the character stored at the location. 2D arrays and pointer variables both can b used to store multiple strings.


1 Answers

Arrays are not pointers. Array names decay to pointers to the first element of the array in certain situations: when you pass it to a function, when you assign it to a pointer, etc. But otherwise arrays are arrays - they exist on the stack, have compile-time sizes that can be determined with sizeof, and all that other good stuff.

like image 121
Chris Lutz Avatar answered Oct 13 '22 00:10

Chris Lutz