Solved

Declare a variable without initialization

Posted on 2003-12-02
4
286 Views
Last Modified: 2010-05-18
Hello,
after declaration of char str[1024]; (without intialization or assignment), what value the str points to? Does char str[1024]; equal to char str[1024]="";? Thanks.
0
Comment
Question by:rongz
  • 2
4 Comments
 
LVL 45

Accepted Solution

by:
sunnycoder earned 50 total points
ID: 9858028
Hi rongz,
> what value the str points to?
str refers to the address of first element of the array ... however, the array itself will contain junk ... it is impossible to tell what are its content. Exceptions are global and static variables which are automatically set to 0s

>Does char str[1024]; equal to char str[1024]="";?
No ... As automatic variable, it will have unpredictable contents

Cheers!
Sunny:o)
0
 

Author Comment

by:rongz
ID: 9858500
However, running the following code, I always get "hit" result. Why?

------------------------------------
#include <string.h>
#include <stdio.h>
void main(int argc, char **argv){
  char max[124];

  if (strcmp(max, "")==0)
    printf("hit\n");
  else
    printf("not hit\n");

}
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 9858559
Memory has a lot of zeros in it. You got lucky.
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 9858587
This typically works too, but you shouldn't depend on it:
--------8<--------
#include <stdio.h>

void foo();
void foo2();

int main()
{
      foo();
      foo2();
}

void foo()
{
char buf[256];

      strcpy(buf,"Hello, World\n");
}

void foo2()
{
char buf[256];

      printf(buf);
}
--------8<--------
0

Featured Post

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.

789 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question